繁体   English   中英

用 while 循环替换低效的 jQuery 代码

[英]Replace non-efficient jQuery code with a while loop

我有以下代码工作 -

$('.sectionHeader:contains(Product Specific Documents)').next('div').find('table').find('input[type="checkbox"]').attr('checked', true);
var attr = $('.sectionHeader:contains(Product Specific Documents)').next('div').next('div').attr('id');
if(typeof attr !== undefined && attr !== false) {
$('.sectionHeader:contains(Product Specific Documents)').next('div').next('div').find('table').find('input[type="checkbox"]').attr('checked', true);
}

它基本上选择/选中特定表格内的复选框。 它工作正常,但看起来很丑。

我想用while循环替换它。 while 循环背后的想法是 -

找到所需的标题(表的)和将该标题分配给变量后的下一个 DIV。 然后我检查一个循环,如果 id 属性存在,如果存在,然后我在其中搜索一个表格,然后在里面搜索复选框并选择它们。 然后我重新分配一个变量,添加下一个 DIV 并在 while 循环中检查它。

所以,代码看起来像 -

var at = $('.sectionHeader:contains(Product Specific Documents)').next('div');
while (typeof at.attr('id') !== undefined || at.attr('id') !== false) {
    at.find('table').find('input[type="checkbox"]').attr('checked', true);
    at = at.next('div');
}

但它不起作用/它与我的初始代码不一样。

var at = $('.sectionHeader:contains(Product Specific Documents)').next('div');
for (var idx = 0; idx < 4 && (typeof at.attr('id') != 'undefined' && at.attr('id') != null); ++idx) {
    at.find('table').find('input[type="checkbox"]').attr('checked', true);
    at = at.next('div');
}

//这个for循环有效

我还发现了为什么 while 循环不起作用 - 因为检查 null 很重要 -

var at = $('.sectionHeader:contains(Product Specific Documents)').next('div');
while (typeof at.attr('id') !== 'undefined' && at.attr('id') != null) {
    at.find('table').find('input[type="checkbox"]').attr('checked', true);
    at = at.next('div');
}

//这个while也有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM