我在页面中有一个消息槽,我在其中显示不同的消息。对于每条消息,我都会运行模板并将该 HTML 附加到消息槽中,如下所示。我添加 html("") 首先清除该框。有更好的方法吗?
$("#message-slot").html("").append(messagetemplate);
最佳答案
就这样做:
$("#message-slot").html(messagetemplate);
它将在替换之前清除所有现有内容 ( reference ):
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content.
顺便说一句,请注意可能附加到您要删除的元素的任何现有事件处理程序。您需要确保解除它们的绑定(bind)。请参阅unbind()
和 remove()
了解更多信息。
关于javascript - 更好的做法 .html ("").append(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18069950/