Javascript 将段落替换为文本区域';s包含现有段落值
我想找到文档中的所有段落,并将它们替换为textarea,其中textarea中的文本是原始内容。我尝试了jquery的.replaceWith()和.contents(),但都不起作用Javascript 将段落替换为文本区域';s包含现有段落值,javascript,jquery,html,Javascript,Jquery,Html,我想找到文档中的所有段落,并将它们替换为textarea,其中textarea中的文本是原始内容。我尝试了jquery的.replaceWith()和.contents(),但都不起作用 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script>
<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>
$(文档).ready(函数(){
$('p,div')。替换为(“+$(this).text()+”);
});
首先
第二
第三
及
$(文档).ready(函数(){
$('p,div').replaceWith(“+$(this).contents().filter(函数(){返回this.nodeType==3}).text()+”);
});
首先
第二
第三
您的$(此)
将引用文档,而不是选择中的当前html元素。
您可以在所有元素之间循环:
$(document).ready(function() {
$('p,div').each(function(){
var $this = $(this);
$this.replaceWith("<textarea rows='4'>" + $this.text() + "</textarea>");
});
});
$(文档).ready(函数(){
$('p,div')。每个(函数(){
var$this=$(this);
$this.replaceWith(“+$this.text()+”);
});
});
您的问题是由于
此
的范围造成的。要使其工作,您需要为replaceWith()
提供一个在集合中每个匹配元素上运行的函数。从这个函数中,您只需要返回HTML以替换原始元素。试试这个:
$('p,div')。替换为(函数(){
返回“”+$(this).text()+“”;
});代码>
首先
第二
第三个
$(document).ready(function() {
$('p,div').each(function(){
var $this = $(this);
$this.replaceWith("<textarea rows='4'>" + $this.text() + "</textarea>");
});
});