【问题标题】:Using $(this) after .replaceWith()在 .replaceWith() 之后使用 $(this)
【发布时间】:2013-06-25 00:54:29
【问题描述】:

请考虑以下 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());
    });
});

【问题讨论】:

    标签: jquery this replacewith


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        试试这个:

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

        【讨论】:

        • 这行不通,.replaceWith() 返回上一个对象,&lt;a&gt;,而不是它所替换的 &lt;p&gt;
        • 那行不通。 replaceWith 方法返回带有原始元素的原始 jQuery 对象,而不是带有新元素的新 jQuery 对象。 api.jquery.com/replaceWith
        猜你喜欢
        • 2013-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多