Using $(this) after .replaceWith()

旧街凉风 提交于 2019-12-14 00:32:42

问题


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.

How can I reference the new element?

HTML:

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

Javascript:

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

回答1:


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());
    });
});



回答2:


You can use the replaceAll method instead, which returns the new content instead of the original content:

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



回答3:


Try this:

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


来源:https://stackoverflow.com/questions/4399424/using-this-after-replacewith

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!