使用 jQuery gt() 和 lt() 访问无法正常工作的元素范围

Posted

技术标签:

【中文标题】使用 jQuery gt() 和 lt() 访问无法正常工作的元素范围【英文标题】:Using jQuery gt() and lt() to access range of elements not working correctly 【发布时间】:2020-06-16 09:10:50 【问题描述】:

我正在尝试将 td 元素的文本推送到数组中以供以后使用。我在 tr 元素的最后一列中的按钮上使用了单击事件(我标记了一个 IP 地址)。

我正在尝试抓取大于 0 且小于 7 的每个元素,但是,我的开发控制台显示最后一个元素仍被抓取,这将是按钮。

这是控制台输出:

    Array Val: xx.xxx.xx.xxx
    Array Val: AT&T
    Array Val: some random text
  3 Array Val: <--- Notice the 3 here? That should the next 3 elements, which is fine
    Array Val: <--- THIS SHOULD NOT BE HERE SINCE IT WASN'T SUPPOSED TO GET PUSHED TO THE ARRAY

这是我创建这个数组的代码:

//Click the button
$('#bAcep').on('click', function() 
    //Get the parent of the parent of the parent of the button, find the 'td' elements
    //between the first and the last (1 - 6).
    var text = $(this).parent().parent().parent().find('td:gt(0):lt(7)');
    //Now add each of those to the array
    text.each(function() 
        array.push($(this).text());
    );
    //Loop through array and print to console
    $.each(array, function(index, val) 
        console.log("Array Val: "+val);
    )
)

【问题讨论】:

【参考方案1】:

更改我的 lt()/gt() 范围修复了它。我还添加了一些调试代码来查看我推送到数组的每个元素的 htmlouterHTML 部分):

$('#bAcep').on('click', function() 
  var text = $(this).parent().parent().parent().find('td:gt(0):lt(6)'); //<-- Changed to 6 instead of 7
  text.each(function() 
    array.push($(this).text());
    console.log("outerHTML: "+$(this).get(0).outerHTML); //<-- Added
  );
$.each(array, function(index, val) 
  console.log("Array Index: " + index + ", Array Val: "+val);
 )
)

它给了我需要的正确索引:

【讨论】:

以上是关于使用 jQuery gt() 和 lt() 访问无法正常工作的元素范围的主要内容,如果未能解决你的问题,请参考以下文章

jquery+jquery.pagination+php+ajax 无刷新分页

使用 jQuery gt() 和 lt() 访问无法正常工作的元素范围

使用 AJAX jQuery 访问 Python Rest API

Jquery无刷新实时更新表格数据

jQuery 单页无刷新插件

如何在 jquery 中访问最近的 p 标签?