javascript - 用包含现有段落值的文本区域替换段落

标签 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>
    $(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/

相关文章:

javascript - 无 Action 的工作形式

html - 如何为我的 CSS 进度条制作动画?

javascript - D3 多层时间轴

javascript - 即使在脚本之前加载 jQuery,Firebug 也会给出 jQuery "$ is undefined"错误

javascript - 在 Qualtrics 中使用运行时数据实时执行简单的数学运算

Jquery next() 没有获取下一个元素

javascript - 菜单重叠在 slider 上

javascript - Apple.com 搜索喜欢 Transitions

javascript - 如何将图像文件 url 上传到 indexedDB 以在页面上呈现

javascript - jQuery 正则表达式测试