将段落替换为包含现有段落值的文本区域



我想在文档中找到所有段落,然后用文本area的文本中的文本中的文本中的文本是原始内容。我尝试了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>

您的$(this)将引用该文档,而不是当前的HTML元素形式。您可以改用所有元素循环:

 $(document).ready(function() {
   $('p,div').each(function(){
   var $this = $(this);
    $this.replaceWith("<textarea rows='4'>" + $this.text() + "</textarea>");
   });
 });

示例

最新更新