我有一个 textarea
和 button
,需要用新的替换。我在 jquery 中使用 replaceWith
来实现此目的,但似乎我做错了。
这是我的 JavaScript:
<script>
$(document).ready(function () {
$(document).on('click', 'div', function(){
$('textarea, button').replaceWith('<textarea>New</textarea><button>Old</button>');
});
});
</script>
我的 HTML:
<textarea>Old</textarea>
<button>Old</button>
<div>Replace</div>
单击Replace
div 应将旧
文本区域和按钮替换为新文本区域和按钮,但由于某种原因,它会导致显示 2 个文本区域和 2 个按钮。
尝试使用 $('textarea', 'button')
但这根本没有任何作用。
最佳答案
如果根据您在其他地方的评论,您无法出于文本目的将两个元素分开,那么您应该确保两个现有元素共享一个共同的父元素(例如 <div>
),然后替换内容 该父级:
<div id="parent">
<textarea>Old</textarea>
<button>Old</button>
</div>
$('#parent').empty().append(newContent);
或者,如果您无法更改下载的 HTML,则在事件处理程序中,如果您可以假设“替换”div 和原始内容之间没有其他匹配元素:
$(this).prevAll('button').first().remove();
$(this).prevAll('textarea').first().remove();
$(this).before(newContent);
关于javascript - 在查询中使用 Replace with 替换多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993604/