jQuery append() - 重复追加
在我将 div 之类的东西附加到 html 主体的场景中,我注意到 jQuery 足够智能,可以防止两次附加对象。
例如,采用以下代码:
$("body").append("<div id=\"divDialog\" title=\"Custom Dialog\">My dialog question?</div>");
$("#divDialog").dialog();
无论我调用上述方法多少次,divDialog 都只会创建一次(据我所知)。
如果您没有运行在紧密循环允许多次调用append方法有什么问题吗?这会导致任何问题吗?
我假设在循环中这是需要避免的......
In a scenario where I am appending something like a div to the html body I have noticed that jQuery is smart enough to prevent appending the object twice.
So for example take the following code:
$("body").append("<div id=\"divDialog\" title=\"Custom Dialog\">My dialog question?</div>");
$("#divDialog").dialog();
No matter how many times I call the above method divDialog will only be created once (from what I can see).
In cases where you are not running in a tight loop is there anything wrong with allowing the append method to be called multiple times? Can this cause any problems?
I am assuming in a loop it would be something to avoid...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,并排运行并没有什么问题。我没有统计数据支持我的观点,但根据经验我可以告诉你,这对性能的影响很小。例外情况是,如果您像循环一样一遍又一遍地使用它,但您说情况并非如此。
如果两者同样简单,更好的方法是连接所有要追加的 HTML 并立即执行。
No, there's nothing wrong at all with running it next to each other. I don't have stats to back me, but from experience I can tell you that there's very little impact on performance. The exception would be if you're using it over and over again like in a loop, but you said that's not the case.
If both are equally easy, the better method would be to concatenate all of the HTML to append and do it at once.