为什么jQuery html在与表单一起使用时像replaceWith一样工作

Why jQuery html works like replaceWith when using with form?

本文关键字:replaceWith 工作 一样 html jQuery 表单 一起 为什么      更新时间:2023-09-26

>我有 id push-message-form 的表单,ajax 调用服务器返回要替换的新表单 html。 push-message-form表单本身上设置的 id,例如:

<form id='push-message-form'>form content</form>

和 Ajax Response HTML 看起来是一样的。

从jQuery文档中我了解到:html()将替换元素的内容,而replaceWith()将替换实际元素。

http://api.jquery.com/html/

http://api.jquery.com/replaceWith/

但我正在使用

$('#push-message-form').html('<form id='push-message-form'>content</form>')

替换表单本身(同时它应该在当前表单中添加另一个表单)。

问题是为什么 html() 在这种情况下作为 replaceWith() 工作?

更新

一些答案建议使用附加,如果不清楚,对不起。但我不想附加。我想用从服务器返回的新表单替换表单(保留其 id),并且 replaceWith() 确实可以正常工作。

问题是为什么html()在这里也有效。因为它应该只替换内容,但它也替换标签。

您应该

使用 .append() 将内容添加到调用容器.html()该容器中的内容,该容器将用您输入的值替换该容器中的任何内容:

此外,您还尝试使用相同的id附加表单,因此您应该使用类或更改 id 名称

这:

$('#push-message-form').append('<form class="push-message-form">content</form>')

取而代之的是:

$('#push-message-form').html('<form id='push-message-form'>content</form>')

.html()直接清除元素内的 HTML,然后将新 HTML 放入其中。虽然您需要.append()才能实际使当前HTML中添加新的HTML

$('#push-message-form').append('<form id='new-form-id'>content</form>')