我是 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/