jQuery 更改多个属性或替换整个 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5151874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:38:54  来源:igfitidea点击:

jQuery change multiple attributes or replace entire html

jqueryoptimization

提问by Timothy Ruhle

I was wondering if it were more efficient/faster to change multiple attributes with jQuery or to just change replace all the html in one go. This is the code i am using at the moment.

我想知道使用 jQuery 更改多个属性是否更有效/更快,或者只是更改一次替换所有 html。这是我目前使用的代码。

// shows the table and changes the image to up
showTable = function(tableId){
    $('#img' + tableId).attr("src", images["up"]).attr("alt", "Hide Table").attr("title", "Hide Table");
    $('#' + tableId).fadeIn(250);
}

or would this be faster?

或者这会更快吗?

// shows the table and changes the image to up
showTable = function(tableId){
    $('#img' + tableId).replaceWith('some html');
    $('#' + tableId).fadeIn(250);
}

回答by yan.kun

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

Example taken from jQuery Documentation.

示例取自jQuery 文档

回答by T.J. Crowder

Given that you're taking a quarter of a second to fade in the result and this isn't a tight loop, you're not going to notice any performance difference between the two. As yan.kun points out, you can make the code a bit more concise by using the multi-set (map) version of attr, but with three attributes not in a tight loop, it's not going to make a speeddifference. (If it were, I'd avoid calling attrentirely and use the element's own reflected properties — src, alt, and titleare all reflected.)

鉴于您需要四分之一秒来淡入结果,而且这不是一个紧密的循环,您不会注意到两者之间的任何性能差异。正如 yan.kun 指出的那样,您可以通过使用 的多集(地图)版本使代码更简洁一些attr,但是由于三个属性不在一个紧密循环中,因此不会产生速度差异。(如果是这样,我会避免调用attr完全和使用元素的体现自身的属性- srcalttitle无一不体现。)

Having said that, there are otherreasons to update elements rather than replace them. For instance, if you have any handlers attached to the elements, if you update the elements' attributes, the handlers remain attached; if you replacethe elements, the handlers aren't attached (because they were attached to the old ones). Replacing elements also causes reflow, which can be significant (or not) depending on your DOM structure.

话虽如此,更新元素而不是替换它们还有其他原因。例如,如果您有任何附加到元素的处理程序,如果您更新元素的属性,处理程序将保持附加;如果替换元素,则不会附加处理程序(因为它们已附加到旧元素)。替换元素也会导致回流,这可能很重要(或不重要),具体取决于您的 DOM 结构。