在.replaceWith()之后使用$(this) [英] Using $(this) after .replaceWith()
本文介绍了在.replaceWith()之后使用$(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下HTML和Javascript.在脚本中,我将 a 标记替换为 p 标记.我期望alert()函数返回 p 标记的内容,但是它将返回不再存在的原始 a 标记的内容.
Please consider the below HTML and Javascript. In the script, I am replacing an a tag with a p tag. I am expecting the alert() function to return the contents of the p tag but instead it returns the contents of the original a tag which no longer exists.
如何引用新元素?
HTML:
<a href="">This is a link</a>
Javascript:
$(document).ready(function() {
$("a").each(function() {
$(this).replaceWith('<p>New Paragraph</p>');
alert($(this).text());
});
});
推荐答案
您不能直接通过 .replaceWith()
,但您可以单独创建它.试试这个:
You can't do it directly with .replaceWith()
, but you can create it separately. Try this:
$(document).ready(function() {
$("a").each(function() {
var p = $('<p>New Paragraph</p>');
$(this).replaceWith(p);
alert(p.text());
});
});
这篇关于在.replaceWith()之后使用$(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文