[英]Comparing “this” object with Object in DOM Array
這個問題是我提問的根本原因。
由於已經發布了兩個答案,我想到了嘗試不同的東西
使用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>
這里做的是將click事件分配給<TH>
元素。 在加載時,我在DOM中獲取DOM中的所有<TH>
。
現在,我的邏輯是。 迭代for循環,如果單擊的TH
不是for loop
中的那個,則隱藏它。
我嘗試的是
if ( thList[i] != $(this)) { thList[i].style.display = 'none' }
但這似乎並沒有起作用。 我需要用什么代碼來比較對象
當您訪問jQuery對象中的項時,您將它們作為DOM元素獲取,而不是作為新的jQuery對象。 因此,您應該直接將它與元素引用進行比較,而不是將元素引用包裝在jQuery對象中:
for (i = 0; i < thList.length; i++) {
if ( thList[i] != this) { thList[i].style.display = 'none' }
}
您還可以使用not
方法獲取沒有當前元素的集合:
thList.not(this).each(function(){ this.style.display = 'none'; });
當然,使用css
方法變得更加簡單:
thList.not(this).css('display', 'none');
注意事項:表格中的單元格並不是真正獨立的元素,您可以隱藏而不會影響表格中的其他單元格。 當您在其中隱藏單元格時,該表可能會顯示意外行為。
除了這個事實,你比如標記不包含任何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-loops並使用.css()
(甚至更專用的方法,如.hide()
)而不是本機.style
- 這應該會顯着縮短您的代碼。
您可以使用:
thList.click(function() {
thList.not(this).css("display", "none");
});
出於性能原因,您可以委派事件:
$("#yourtable").on("click", "th", function(event) {
thList.not(event.target).css("display", "none");
});
我沒有測試它,但應該有效。
但是我對UI很好奇:如果TH以這種方式隱藏,在第一次點擊它們之后就不再顯示了它們。
1 -您$(this)
是diferent的this
一次是一個jQuery對象2 -你不必在這里一個個元素的代碼相似,你想,但絲毫TD的
$(function(){
var tdList = $('td');
$('td').click(function(){
tdList.hide();
$(this).show();
//OR tdList.not(this).hide();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.