2013-08-23 44 views
0

我對查找方法有疑問。如何查找包含在表中的輸入標籤

我希望能夠識別包含input標記的單元格。

我的HTML就像

<table> 
    <tr> 
     <td> celll </td> 
     <td> celll </td> 
     <td> celll </td> 
    </tr> 
    <tr> 
     <td> celll </td> 
     <td> <span><input type='text'></span> </td> 
     <td> <span><input type='text'></span> </td> 
    </tr> 
</table> 

我的Jquery

$('table').find('td').each(function(){ 
      if($(this).find("input").length){ 
      console.log('found') 
      } 
     }) 

我的代碼似乎無法找到它。有小費嗎?非常感謝!

+2

似乎爲我工作... http://jsfiddle.net/wM2Tg/ –

+0

「識別細胞」 奇異?或所有細胞? –

+0

.length基本上需要一個參數。如果輸入在那裏,那麼長度將大於0.所以如果($(this).find(「input」).length> 0)可以工作。 – peterchon

回答

1

而不是使用.find()兩次,只使用了一次,得到.closest()細胞:

$('table').find('input').each(function(){ 
    var parent = $(this).closest('td'); 
    //do something with parent 
}); 

DEMO: http://jsfiddle.net/dirtyd77/kdL97/

0

只需使用:$('table input').parents('td');

的jsfiddle:http://jsfiddle.net/aPjwE/

+0

@Dom它確實。你的jsfiddle不使用我的代碼。看到我的jsfiddle編輯。 –

+0

@ jimjimmy1995'$('table')。find('input')'比'$('table input')'有更好的性能。 –

0
var cells = $('table').find('td'); 

$.each(cells, function(i){ 
    var that = $(this); 
    var hasInput = that.find("input"); 
    if(hasInput.length > 0){ 
     console.log("td #" + i + " has an input sire."); 
    } 
}); 
相關問題