简体   繁体   English

用包含现有段落值的textarea替换段落

[英]Replace paragraphs with textarea's containing existing paragraph value

I want to find all paragraphs within a document and replace them with textarea's where the text inside the textarea is the original content. 我想在文档中找到所有段落,并用textarea替换它们,其中textarea内的文本是原始内容。 I've tried jquery's .replaceWith() and .contents() but neither work. 我试过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>

AND

<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>

Your issue is due to the scope of this . 您的问题是由于this问题引起的。 For it to work you need to provide replaceWith() with a function that runs on each matched element in the set. 为了使其正常工作,您需要为replaceWith()提供一个在集合中每个匹配元素上运行的函数。 From this function you just need to return the HTML to replace the original element with. 通过此函数,您只需要返回HTML即可替换原始元素。 Try this: 尝试这个:

 $('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> 

Your $(this) will be referring to the document and not to the current html element form the selection. 您的$(this)将引用文档,而不是所选内容中的当前html元素。 You can loop through all elements instead: 您可以遍历所有元素:

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

Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM