jquery 将元素替换为具有自己文本的新元素

标签 jquery html

我是 jquery 的新手,只是在尝试学习。 我正在尝试将所有 < p> 元素更改为 < button> 元素,并使用与其相应的 p 元素相同的文本。

如果我有这个 html:

<p>Hello</p>
<p>Here is a paragraph</p>
<p>And Another</p>

我想把它改成这样:

<button>Hello</button>
<button>Here is a paragraph</button>
<button>And Another</button>

但是,我的 jquery 代码同时选择所有 < p> 元素的文本,因此我得到以下结果:

<button>Hello Here is a paragraph And Another</button>
<button>Hello Here is a paragraph And Another</button>
<button>Hello Here is a paragraph And Another</button>

我做错了什么?这是我的 jquery/javascript:

var ChangeToButton = function () {
    $("p").replaceWith ("<button>" + $("this").text() + "</button>");
}

$("button").on("click", function (event) {
    ChangeToButton();
});

感谢您对此提供的任何帮助。

最佳答案

尝试使用.replaceWith()的接收函数,

$("p").replaceWith (function(_,content){ 
    return "<button>" + content + "</button>" 
});

DEMO

关于jquery 将元素替换为具有自己文本的新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25029013/

相关文章:

javascript - 如何获取其他Frame中的隐藏值?

javascript - 在 jquery 插件的函数中使用当前元素

jquery - 由自定义 jQuery 验证错误标签引起的不需要的空间

javascript - 我怎样才能给菜单项激活类

javascript - 使用 HTML 和 CSS 将图像放置到 Circle 中

javascript - 当我调整浏览器窗口大小时,我的图像在它们应该保持在一起时移动了

jquery - 悬停事件和父项的问题

javascript - css3 图像淡入淡出

javascript - 本地址栏出现时,android 上的 css 固定页脚被隐藏

css - 图像适合窗口