代码之家  ›  专栏  ›  技术社区  ›  Marcus Aurelio

是否可以在加载HTML内容后替换HTML内容?

  •  -2
  • Marcus Aurelio  · 技术社区  · 8 年前

    我有以下由SiteCore内容管理生成的html:

    <input aria-label="Username is required." class="form" id="Username" name="Username" type="text" value="" aria-required="true">
    

    我想做的是用以下内容替换上述内容:

    <input aria-label="Email is required." class="form" id="Email" name="Email" type="text" value="" aria-required="true">
    

    如何使用jquery或纯javascript实现这一点?

    理想情况下,我希望在加载文档后立即替换html。

    1 回复  |  直到 8 年前
        1
  •  1
  •   j6m8    8 年前

    查看JQuery .replaceWith() 功能,其设计正是为了此目的: https://api.jquery.com/replaceWith/

    您可以这样做:

    $('#Username').replaceWith( [ new html here ]);
    

    使用 $.ready() 用于检测文档何时满载的功能: https://api.jquery.com/jQuery.ready/

    $.when( $.ready ).then(function() {
        // Document is ready.
        $('#Username').replaceWith(`
            <input aria-label="Email is required." class="form" id="Email" name="Email" type="text" value="" aria-required="true">
        `);
    });
    

    请记住,在加载文档后编辑自动生成的HTML并不是一个好主意,因为它会使UI与后端期望存在的内容不同步。您可能想看看是否有办法更改生成器输出的代码,因为这种方法非常脆弱。