简体   繁体   English

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

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

I have the following code working -我有以下代码工作 -

$('.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);
}

It basically selecting/checking checkboxes inside a specific table(s).它基本上选择/选中特定表格内的复选框。 It works fine but looks ugly.它工作正常,但看起来很丑。

I'd like to replace it with a while loop.我想用while循环替换它。 The idea behind while loop is - while 循环背后的想法是 -

Find the required header (of table) and next DIV after that header is assigned to a variable.找到所需的标题(表的)和将该标题分配给变量后的下一个 DIV。 Then I check in a loop if id attribute exists and if yes, then I search for a table inside it then checkboxes inside and selecting them.然后我检查一个循环,如果 id 属性存在,如果存在,然后我在其中搜索一个表格,然后在里面搜索复选框并选择它们。 Then I'm reassigning a variable adding next DIV and checking it in while loop.然后我重新分配一个变量,添加下一个 DIV 并在 while 循环中检查它。

So, the code looks like -所以,代码看起来像 -

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');
}

But it doesn't work / it doesn't do the same as my initial code.但它不起作用/它与我的初始代码不一样。

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');
}

//This for loop works //这个for循环有效

I also found why while loop wasn't working - because the check for null was important -我还发现了为什么 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');
}

//This while also works //这个while也有效

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

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