Jquery 在.replaceWith()之后使用$(this) 请考虑下面的HTML和JavaScript。在脚本中,我将用p标记替换a标记。我希望alert()函数返回p标记的内容,但它返回的是原始a标记的内容,该标记已不存在

Jquery 在.replaceWith()之后使用$(this) 请考虑下面的HTML和JavaScript。在脚本中,我将用p标记替换a标记。我希望alert()函数返回p标记的内容,但它返回的是原始a标记的内容,该标记已不存在,jquery,this,replacewith,Jquery,This,Replacewith,如何引用新元素 HTML: <a href="">This is a link</a> $(document).ready(function() { $("a").each(function() { $(this).replaceWith('<p>New Paragraph</p>'); alert($(this).text()); }); }); Javascript: <a href

如何引用新元素

HTML:

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

Javascript:

<a href="">This is a link</a>
$(document).ready(function() {
    $("a").each(function() {
        $(this).replaceWith('<p>New Paragraph</p>');
        alert($(this).text());
    });
});
$(文档).ready(函数(){
$(“a”)。每个(函数(){
$(此)。替换为(“新段落”);
警报($(this.text());
});
});
试试这个:

alert($(this).replaceWith('<p>New Paragraph</p>').text());
$(document).ready(function() {
    $("a").each(function() {
        var p = $('<p>New Paragraph</p>');
        $(this).replaceWith(p);
        alert(p.text());
    });
});
警报($(this).replace为(“新段落”).text();

您不能直接使用,但可以单独创建。试试这个:

$(document).ready(function() {
    $("a").each(function() {
        var p = $('<p>New Paragraph</p>');
        $(this).replaceWith(p);
        alert(p.text());
    });
});
$(文档).ready(函数(){
$(“a”)。每个(函数(){
var p=$(“新段落”

”); 美元(本)。替换为(p); 警报(p.text()); }); });
您可以改用
replaceAll
方法,该方法返回新内容而不是原始内容:

$(document).ready(function() {
  $("a").each(function() {
    alert($('<p>New Paragraph</p>').replaceAll($(this)).text());
  });
});
$(文档).ready(函数(){
$(“a”)。每个(函数(){
警报($('新段落

).replaceAll($(此)).text(); }); });
这不起作用,
.replaceWith()
返回上一个对象,即
,而不是它所替换的
。这不起作用。
replaceWith
方法返回带有原始元素的原始jQuery对象,而不是带有新元素的新jQuery对象。