我想找到文档中的所有段落并将它们替换为 textarea,其中 textarea 中的文本是原始内容。我试过 jquery 的 .replaceWith() 和 .contents() 但都不起作用。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('p,div').replaceWith("<textarea rows='4'>" + $(this).text() + "</textarea>");
});
</script>
</head>
<body>
<p>first</p>
<p>second</p>
<p>third</p>
</body>
</html>
和
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('p,div').replaceWith("<textarea rows='4'>" + $(this).contents().filter(function () { return this.nodeType === 3 }).text() + "</textarea>");
});
</script>
</head>
<body>
<p>first</p>
<p>second</p>
<p>third</p>
</body>
</html>
最佳答案
您的问题是由于 this
的范围造成的。为了让它工作,您需要为 replaceWith()
提供一个函数,该函数在集合中的每个匹配元素上运行。从这个函数中,您只需要返回 HTML 来替换原始元素。试试这个:
$('p, div').replaceWith(function() {
return '<textarea rows="4">' + $(this).text() + '</textarea>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>first</p>
<p>second</p>
<p>third</p>
关于javascript - 用包含现有段落值的文本区域替换段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42789114/