2012-07-10 45 views
2

這個問題是我的問題的根本原因。在DOM數組中比較「this」對象與對象

Hide all next tr td until next tr th

正如已經被張貼兩個答案,我想嘗試不同的東西

的Javascript:

$(function(){ 
    var thList = $('td'); 
    $('td').click(function(){ 
     for(i =0; i < thList.length;i++){ 
      // What to do here 
     } 
    }); 
}); 

HTML:

<table border="2"> 
     <tr> 
      <td> 1 </td> 
      <td> 2 </td> 
      <td> 3 </td> 
     </tr> 
    <table> 

什麼我在這裏做什麼是 點擊事件到<TH>元素。在加載時,我需要在DOM中獲取DOM中的所有<TH>

現在,我的邏輯是。迭代for循環,如果點擊的TH不是for loop中的那個,則隱藏它。

是我的嘗試是

if (thList[i] != $(this)) { thList[i].style.display = 'none' } 

但這似乎並不奏效。我需要放置哪些代碼來比較對象

+0

是'是th'元素在**頁面加載後添加** – Lix 2012-07-10 14:26:13

+0

從您發佈的代碼看來,點擊的'TH'將總是*在* thList'數組中。 – James 2012-07-10 14:26:16

+0

除非我誤解了這個問題,否則你不需要跳過循環來實現你想要的。在點擊處理程序中$(this)已經引用了被點擊的元素。 – Dimitri 2012-07-10 14:27:13

回答

2

除了這個事實,你比如標記不包含任何th -elements,你可以嘗試以下方法:

$('td').click(function(){ 

    var $tdList = $('td').not(this); // <- get all th's and exlude the clicked element 

    $tdList.each(function(){this.style.display = 'none'; }); 
}); 

,甚至更好,使用jQuery,你不需要每個包裝則:

$tdList.hide(); 

因爲jQuery的爲您節省了大量的工作,嘗試使用它時,你可以 - 使用each()代替for循環,並使用.css()(或更專門的方法,如.hide()),而不是NAT ive .style - 這會顯着縮短您的代碼。

+0

對不起。錯字:更新:) – madhairsilence 2012-07-10 14:34:21

2

當您訪問jQuery對象中的項目時,將它們作爲DOM元素訪問,而不是作爲新的jQuery對象。所以,你應該直接把它比作元素參考,不包裝在一個jQuery對象中的元素參考:

for (i = 0; i < thList.length; i++) { 
    if (thList[i] != this) { thList[i].style.display = 'none' } 
} 

您還可以使用not method得到一個集合,而不當前元素:

thList.not(this).each(function(){ this.style.display = 'none'; }); 

當然,使用css method它變得更簡單:

thList.not(this).css('display', 'none'); 

謹慎的說法:表中的單元格不是真正獨立的元素,您可以在不影響表格中的其他單元的情況下隱藏它們。當您隱藏單元格時,該表可能會顯示意外的行爲。

+0

Yeh。嘗試過但不工作。但如果沒有錯。當我綁定一個jQuery事件,我將得到jQuery的包裝,而不是正常的DOM對象的 – madhairsilence 2012-07-10 14:30:34

+0

$( '日')。點擊(函數(){ \t \t \t \t \t thList.not(本)。每個(函數( ){alert(''); this.style.display ='none';}); \t \t \t \t}); 這是你的意思。對不起:(不工作!) – madhairsilence 2012-07-10 14:32:38

+0

@madhairsilence:在jQuery事件中,'this'是對DOM元素的引用,而不是對包含元素的jQuery對象的引用,我嘗試了兩個版本,並且它們工作:http:// jsfiddle.net/Guffa/ddMWd/ – Guffa 2012-07-10 14:36:04

2

您可以使用:

thList.click(function() { 
    thList.not(this).css("display", "none"); 
}); 

出於性能方面的原因,你可以委託事件,而不是:

$("#yourtable").on("click", "th", function(event) { 
    thList.not(event.target).css("display", "none"); 
}); 

我沒有測試,但應該工作。

但是我對UI感到好奇:如果TH以這種方式隱藏起來,那麼在第一次點擊它們之後就不能再顯示了。

2

1 - 您$(this)this diferent曾經是一個jQuery對象 2 - 你不必在這裏一個個元素的代碼相似,你想,但絲毫TD的

$(function(){ 
var tdList = $('td'); 
$('td').click(function(){ 
    tdList.hide(); 
    $(this).show(); 
    //OR tdList.not(this).hide(); 

    }); 
}); 
+0

簡單而輝煌。 – madhairsilence 2012-07-10 14:44:39

+0

看起來不錯,我寧願'tdList.not(this).hide();'雖然。 – Christoph 2012-07-10 15:27:46