[英]How to iterate over htmlCollection
我對此有些困難。 在Backbone中,我有一個這樣的函數:
functionOne: function(){
$('#myTExtbox-' + budgetLine.attr('id')).on('change keyup paste', function(){
that.mySecondFunction(this);
});
}
在這種情況下, this
是一個textbox
,它位於div
中的table
。 然后:
mySecondFunction: function(tb){
var tbody = tb.parentElement.parentElement.parentElement.parentElement.parentElement;
//gets main parent, which is a tbody, inside a table, inside a div
}
然后我想迭代tbody
,遍歷每一行並在特定單元格中找到一個textbox
。 問題是這段代碼:
$.each(tbody, function(index, item){
cost = item;
var t= index;
});
似乎不允許我去任何項目。 在這個例子中,如果我嘗試做類似的事情:
item.getElementById('test');
我收到一個錯誤:
TypeError: Object #<HTMLCollection> has no method 'getElementById'
為什么我不能迭代這個對象並訪問其中的對象?
謝謝
UPDATE
這是一個小提琴: http : //jsfiddle.net/HX8RL/14/
本質上,應該發生的是:當文本框發生變化時,我想迭代tb父表中的所有行並總結所有Tb值。 請記住,所有tb都處於相同的單元格位置,因為在其他地方我可能不想包含其他tb。
不會有任何TBody
集合嘗試使用children()
代替
$.each(tbody.children('tr'), function(index, item){
cost = item;
var t= index;
});
直接迭代所有輸入元素以獲取值。
var tbody = tb.parentElement.parentElement.parentElement;
alert(tbody.id);
var input = $('#tbody').find('input');
alert(input);
console.log(input);
for (var i = 0; i < input.length; i++) {
alert(input[i].value);
alert(i);
}
我認為這里有一些問題。 你知道每頁只能有一個ID嗎? 所以你必須改為使用document.getElementByid('test')
。
由於您還使用jQuery,因此可以使用find函數item.find('#test')
。 但我認為這不會解決你的問題。 不知道你想要達到什么目標,如果你詳細解釋一下你的問題是什么,也許我會幫助你。
也
tb.parentElement.parentElement.parentElement.parentElement.parentElement;
可以寫成(在jQuery中)
$(tb).parents('tbody');
我已經設置了一個小提琴 ,也許它可以幫助你。
小提琴中使用的代碼:
var myFuncs = (function() {
function funcA() {
$('input').on('keyup', function() {
funcB(this);
});
}
function funcB(myInput) {
var $table = $(myInput).parents('table');
$table.find('tr > td > input').each(function() {
var $input = $(this);
if($(myInput).attr('id') != $input.attr('id'))
$input.val("I'm called from another input");
});
}
return {
funcA : funcA
}
})();
myFuncs.funcA();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.