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

请考虑以下 HTMLJavascript.在脚本中,我正在用p标签替换标签.我期望alert()函数返回p标记内容,但它返回原始标记内容,该标记不再存在.

我如何引用新元素?

HTML:

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

使用Javascript:

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

解决方法

你不能直接使用 .replaceWith(),但你可以单独创建它.试试这个:
$(document).ready(function() {
    $("a").each(function() {
        var p = $('<p>New Paragraph</p>');
        $(this).replaceWith(p);
        alert(p.text());
    });
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...