gpt4 book ai didi

jquery - 此页面上的脚本导致 Internet Explorer 运行缓慢

转载 作者:行者123 更新时间:2023-12-01 04:12:52 25 4
gpt4 key购买 nike

我有 jQuery 代码:

...
var poleVstupu= {id:['31'],platny:['1'],datum:['2013-08-05 20:23:38'], ... };

for(var poleName in poleVstupu)
{
$('[name='+poleName+']').val(poleVstupu[poleName]).change();
}
...

在 Firefox 中,这段代码工作正常,但在 IE8 中,它会抛出 ...run Slow 消息。如果我运行 IE 内置调试​​器,在 ...run Slow 消息之后它会抛出 object does not support this property or method ,但如果我在 设置断点>$('[name='+poleName ... 行,它不显示 object does not ... 消息。

如何才能更快地处理代码并防止显示 ...运行缓慢 消息?

最佳答案

我正在回复此答案中的评论,因为它会更长并且包含代码,但它很可能不会是答案。

<小时/>

浏览器很可能不会为 name 属性建立索引,因此每次都必须循环遍历文档中的每个元素才能找到匹配的名称。如果您将搜索限制在表单内,您可能会获得更好的性能。示例:

var form = $("#form_id");

for(var poleName in poleVstupu)
{
form.find('[name='+poleName+']').val(poleVstupu[poleName]).change();
}
<小时/>

(部分)非 jQuery 解决方案可能是直接从 DOM 访问表单元素。示例:

var form = $("#form_id")[0]; // Get the DOM reference of the form

for(var poleName in poleVstupu)
{
jQuery(form.elements[poleName]).val(poleVstupu[poleName]).change();
}
<小时/>

它还可以帮助您循环遍历表单元素而不是对象。示例:

var form = $("#form_id")[0]; // Get the DOM reference of the form

for (var i = 0, len = form.elements.length; i < len; i++)
{
var element = form.elements[i];
if (typeof poleVstupu[element.name] !== "undefined")
jQuery(element).val(poleVstupu[element.name]).change();
}
<小时/>

jQuery 的性能随着每个版本的增加而提高。不能使用 1.10.x 甚至 2.x 吗?

<小时/>

如果省略.change(),性能如何?

<小时/>

编辑:

在非表单元素上 name 无论如何都是无效的,所以你不应该使用它。我将使用 id 并在需要执行此操作的所有元素上设置一个类:

$(".change-html").each(function() {
if (typeof poleVstupu[this.id] !== "undefined") {
$(this).html(poleVstupu[element.name]);
}
});

或者,如果您无法使用 ID(例如,因为有重复项),请使用 data- attribute .

<p data-change-html="your_name"></p>

$("[data-change-html]").each(function() {
var element = $(this);
var name = element.data("change-html");
if (typeof poleVstupu[name] !== "undefined") {
element.html(poleVstupu[name]);
}
});

(但后者通常不会很快)。

关于jquery - 此页面上的脚本导致 Internet Explorer 运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18311826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com