9

请考虑以下 HTML 和 Javascript。在脚本中,我将a标签替换为p标签。我期望 alert() 函数返回p标签的内容,但它返回的是不再存在的原始a标签的内容。

如何引用新元素?

HTML:

<a href="">This is a link</a>

Javascript:

$(document).ready(function() {
    $("a").each(function() {
        $(this).replaceWith('<p>New Paragraph</p>');
        alert($(this).text());
    });
});
4

3 回答 3

11

你不能直接用 来做.replaceWith(),但你可以单独创建它。试试这个:

$(document).ready(function() {
    $("a").each(function() {
        var p = $('<p>New Paragraph</p>');
        $(this).replaceWith(p);
        alert(p.text());
    });
});
于 2010-12-09T14:47:08.793 回答
2

您可以改用该replaceAll方法,它返回新内容而不是原始内容:

$(document).ready(function() {
  $("a").each(function() {
    alert($('<p>New Paragraph</p>').replaceAll($(this)).text());
  });
});
于 2010-12-09T14:53:30.493 回答
0

试试这个:

alert($(this).replaceWith('<p>New Paragraph</p>').text());
于 2010-12-09T14:44:51.227 回答