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

Is it possible to replace HTML content after it has been loaded?

我有以下由 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。

查看 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 与后端预期存在的内容不同步。您可能想看看是否有办法更改您的生成器吐出的代码,因为这种方法相当脆弱。