2014-09-04 92 views
0

我不知道爲什麼會發生這種情況,我列出了代碼工作的兩種方法,另一種方法沒有。 如果可能的話,我希望得到這個EACH裏面的值,所以我可以改變它的值,但是我可以從外面選擇它們來做所有IMG的每個IMG,這使我失去了與TD有關的參考IMG。jQuery選擇返回undefined

http://jsfiddle.net/4w8030th/1/

// Cannot retrieve SRC inside IMG tag 
$.each($('tr.infraTrClara'), function() { 
    // Post-It 
    var postit = $(this).children('td:nth-child(2)').select('img'); 
    postit_src = $(postit).attr('src'); 
    alert(postit_src); 
}); 

// Can retrieve SRC inside IMG tag 
$.each($('tr.infraTrClara td:nth-child(2) img'), function() { 
    // Post-It 
    var postit = $(this).attr('src'); 
    alert(postit); 
}); 
+1

變化'.select'到'.find'。 – 2014-09-04 17:59:28

回答

2

這種情況的合適方法是.find()而不是.children().select()

然後,由於這將是一個多個結果,而不是將其設置爲一變量,在其上執行的.each()太:

http://jsfiddle.net/4w8030th/3/

$.each($('tr.infraTrClara'), function() { 
    // Post-It 
    $(this).find('td:nth-child(2)').find('img').each(function() { 
     postit_src = $(this).attr('src'); 
     alert(postit_src); 
    }); 
}); 

EDIT

凱文製成評論中的一個很好的觀點。我假設你需要從您發佈(即工作)第二代碼不同的解決方案,還有另外一個原因......

不過,你提到你不想

失去了與該IMG相關的TD的參考。

所以,如果你想一切都操縱td,用你的第二個代碼,並使用parent()稱之爲:

$.each($('tr.infraTrClara td:nth-child(2) img'), function() { 
    // Post-It 
    var postit = $(this).attr('src'); 
    alert(postit); 

    var td = $(this).parent(); //HERE!!! 
}); 
+0

爲什麼找到比孩子更適合的方式?他是否在某個地方包含了html,這表明他在單元格中不僅僅是一個img?我認爲他自己的第二次嘗試比使用查找或孩子更好。 – 2014-09-04 18:08:06

+0

也許我錯誤地表達了......適合不是這個詞,但是'find'比'children'快。 http://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery – LcSalazar 2014-09-04 18:11:39

3

.select()是一個事件監聽器結合的方法,類似於.click()。您可能需要.children()以實現相同的行爲。