在.replaceWith()之后使用$(this)
请考虑以下HTML和Javascript。 在脚本中,我正在用p标签替换标签。 我期望alert()函数返回p标记的内容,但它返回原始标记的内容,该标记不再存在。
我如何引用新元素?
HTML:
This is a link
使用Javascript:
$(document).ready(function() { $("a").each(function() { $(this).replaceWith('New Paragraph
'); alert($(this).text()); }); });
你不能直接用.replaceWith()
来做,但你可以单独创建它。 试试这个:
$(document).ready(function() { $("a").each(function() { var p = $('New Paragraph
'); $(this).replaceWith(p); alert(p.text()); }); });
您可以使用replaceAll
方法,它返回新内容而不是原始内容:
$(document).ready(function() { $("a").each(function() { alert($('New Paragraph
').replaceAll($(this)).text()); }); });
试试这个:
alert($(this).replaceWith('New Paragraph
').text());