在.replaceWith()之后使用$(this)

时间:2010-12-09 14:42:37

标签: jquery this replacewith

请考虑以下HTML和Javascript。在脚本中,我使用 p 标记替换 a 标记。我期望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());
    });
});

3 个答案:

答案 0 :(得分:10)

您无法直接使用.replaceWith()进行此操作,但可以单独创建。试试这个:

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

试试这个:

alert($(this).replaceWith('<p>New Paragraph</p>').text());
相关问题