Javascript 如何使用jquery将ID添加到现有表中?
我希望在dom中循环并向现有的表元素添加ID属性。似乎不能让它正常工作。基本上,代码会查找具有特定类的表,然后添加ID。根据tables类的不同,还会发生更多的事情,但目前我仍无法添加ID。如果您能提供任何帮助,我们将不胜感激Javascript 如何使用jquery将ID添加到现有表中?,javascript,jquery,Javascript,Jquery,我希望在dom中循环并向现有的表元素添加ID属性。似乎不能让它正常工作。基本上,代码会查找具有特定类的表,然后添加ID。根据tables类的不同,还会发生更多的事情,但目前我仍无法添加ID。如果您能提供任何帮助,我们将不胜感激 $(document).ready(function () { var chartTypeArray = []; var i = 0; // cycle tables add id and store class $('tabl
$(document).ready(function () {
var chartTypeArray = [];
var i = 0;
// cycle tables add id and store class
$('table').each(function (i) {
if ($(this).hasClass('bar')) {
chartTypeArray.push('bar');
$(this).attr('ID', 'tableToChart' + i);
} //end bar
else if ($(this).hasClass('line')) {
chartTypeArray.push('line');
$(this).attr('ID', 'tableToChart' + i);
} //end line
else if ($(this).hasClass('area')) {
chartTypeArray.push('area');
$(this).attr('ID', 'tableToChart' + i);
} //end area
else if ($(this).hasClass('pie')) {
chartTypeArray.push('pie');
$(this).attr('ID', 'tableToChart' + i);
} //end pie
i++;
console.log('Table ' + i + ' is a ' + $(this).attr('class') + ' chart');
}); //end function
}); //end of document ready
用小写字母试试
$(this).attr('id', 'tableToChart' + i);
你也不必这么做
var i = 0; //outside the each loop
// and you don't need
i++; // inside the each loop
谢谢你的回答,卡兰巴,虽然那没有任何区别。@woody的问题一定是Som,还有什么,在这里添加id和读取id:如果你需要更多帮助,请用你的markupCaramba创建一把小提琴你这个邪恶的天才!是不必要的增量i=0和i++导致了问题。我当然不需要它们,我在想什么?非常感谢@woody很好,很高兴它有帮助,很高兴编码!