比较“;这个“;DOM数组中具有object的对象

Comparing "this" object with Object in DOM Array

本文关键字:object 对象 数组 这个 DOM 比较      更新时间:2023-09-26

这个问题是我提出这个问题的根本原因。

隐藏所有下一个tr td直到下一个trth

由于已经发布了两个答案,我想尝试一些不同的

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中的所有<TH>

现在,我的逻辑是。迭代for循环,如果单击的TH不是for loop中的那个,那么隐藏它。

我试过的是

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

但这似乎并不奏效。我需要在那里放什么代码来比较对象

除了示例标记不包含任何th-元素之外,您还可以尝试以下操作:

$('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()而不是循环,使用.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");
});

我没有测试,但应该有效。

然而,我对用户界面很好奇:如果TH以这种方式隐藏,那么在第一次点击其中任何一个后,它们都无法再显示。

1-您的$(this)this不同一次是jquery对象2-你没有TH元素,这是你想要的类似代码,但有td的

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

当您访问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');

注意:表中的单元格并不是真正独立的元素,您可以在不影响表中其他单元格的情况下隐藏这些元素。当您将单元格隐藏在表中时,该表可能会显示意外行为。