Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将段落替换为文本区域';s包含现有段落值_Javascript_Jquery_Html - Fatal编程技术网

Javascript 将段落替换为文本区域';s包含现有段落值

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>

我想找到文档中的所有段落,并将它们替换为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>

$(文档).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>");
   });
 });