[英]iterate through span id's passing id as value to function
Supposing I have a table that has been dynamically generated with one of the columns having a unique span id: 假设我有一个表,该表是使用具有唯一跨度ID的列之一动态生成的:
<tr><td><span id="123"></span></td></tr>
<tr><td><span id="124"></span></td></tr>
<tr><td><span id="125"></span></td></tr>
<tr><td><span id="126"></span></td></tr>
What is the best way to iterate through the spans with a javascript function so that the span id can be passed as a value that the function can then use? 用javascript函数遍历跨度的最佳方法是什么,以便可以将跨度id传递为函数可以使用的值?
Assign a same class to each of the span items and then make use of getElementsByClassName and iterate through the array. 为每个范围项分配一个相同的类,然后使用getElementsByClassName并遍历数组。
var targetElements = document.getElementsByClassName('target');
Update (with jQuery) 更新(使用jQuery)
You may be able to use iterate through this using the following code as well. 您也许还可以使用以下代码来使用此迭代。
jQuery('table td > span').each(function() {
var id = jQuery(this).attr('id');
// Your logic
});
Use the jQuery each
function to iterate over your span
s and do something with their id
property: 使用jQuery
each
函数来遍历span
,并使用其id
属性进行操作:
$('#table-id span').each(handleElement) function handleElement () { var id = this.id // Do something with `id` console.log(id) }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="table-id"> <tr><td><span id="123"></span></td></tr> <tr><td><span id="124"></span></td></tr> <tr><td><span id="125"></span></td></tr> <tr><td><span id="126"></span></td></tr> </table>
Use the jquery loop construct to loop through the table data. 使用jquery循环结构循环遍历表数据。
$("tr td").each(function() { var foo = $(this).find("span").attr('id'); }); $(“ tr td”)。each(function(){var foo = $(this).find(“ span”)。attr('id');});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.