简体   繁体   English

遍历表格以查找特定的ID

[英]Loop through a table to find specific id's

I have a table that I'm trying to insert a paypal button in the last cell of the table which is blank. 我有一个表,我试图在表的最后一个单元格中插入一个贝宝按钮,该单元格为空。 I'm not sure how many rows will be in the table and I have the id's hard coded now which works. 我不确定该表中将有多少行,并且我已经对该ID进行了硬编码,从而可以正常工作。 The id's begin with el and a number for each row then _qryMyReservedSlots_Payment ID以el开头,每行都有一个数字,然后是_qryMyReservedSlots_Payment

['#el1_qryMyReservedSlots_Payment', '#el2_qryMyReservedSlots_Payment', '#el3_qryMyReservedSlots_Payment'].forEach(function(selector) {
        paypal.Button.render({ 
        ...paypal code...
        });
});  

to be more efficient, how can I loop through the id's so I don't have to hard code them? 为了提高效率,我该如何遍历id而不用硬编码它们?
Scott 史考特

Use a for loop: 使用for循环:

for (var el = 1; el < 4; el++) {
    var selector = `#el${el}_qryMyReservedSlots_Payment`
    ...
}

or more old-fashioned: 或更老式的:

for (var el = 1; el < 4; el++) {
    var selector = '#el' + el + '_qryMyReservedSlots_Payment'
    ...
}

I'm not sure how many rows will be in the table and I have the id's hard coded now which works 我不确定表中将有多少行,并且我已经对ID进行了硬编码,可以正常工作

Use querySelectorAll and attribute contains selector - * 使用querySelectorAll并且属性包含选择器- *

var allRows = document.querySelectorAll( "tr[id*='qryMyReservedSlots_Payment']");
Array.from( allRows ).forEach( function(rowElement){
  //logic with rowElement
})

Do you need them to have unique ids ? 您是否需要它们具有唯一的ID? You should give them a class and then do something like document.getElementsByClassName(className).forEach(...) . 您应该给他们一个类,然后执行诸如document.getElementsByClassName(className).forEach(...)

If you insist on having unique ids (which, again, is not needed and this is exactly one of the reasons why we have classes), your could would be something like this: 如果您坚持拥有唯一的ID(再次不需要,而这恰恰是我们拥有类的原因之一),则可能是这样的:

while (document.getElementById(`el${ counter++ }_qryMyReservedSlots_Payment`)) {
  paypal.Button.render({ 
    ...paypal code...
  });
}

Again, this is not good because each time you query the id, you are hitting the DOM. 同样,这也不是一件好事,因为每次查询id时,您都在访问DOM。 You should really get it all at once, manipulate in-memory, and then commit all your changes in as few DOM calls as possible. 您应该真正一次获得所有内容,在内存中进行操作,然后在尽可能少的DOM调用中提交所有更改。

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

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