【问题标题】:JQuery get the nth element of arrayjQuery获取数组的第n个元素
【发布时间】:2012-05-13 02:57:10
【问题描述】:
$('#button').click(function() {
   alert($('.column').val());
});

如何获取.column 中的第一个、第二个或第三个元素?

【问题讨论】:

  • 您想要第一个、第二个或第三个意思是这三个中的任何一个吗?或者你想要所有这些?你是指三个元素的类.column,还是三个元素.column元素?

标签: jquery arrays


【解决方案1】:
$('#button').click(function() {
    alert($('.column').eq(0).val()); // first element
    alert($('.column').eq(1).val()); // second
    alert($('.column').eq(2).val()); // third
});

【讨论】:

  • 正如文档:“将匹配元素集减少到指定索引处的元素。” jQuery.eq()
【解决方案2】:

我喜欢选择器字符串,所以我通常这样做:

$('.column:eq(3)') // Fourth .column element

【讨论】:

  • 我喜欢它们纯粹是为了风格,但应该注意的是,jQuery 文档推荐 .eq() 而不是 :eq() 在现代浏览器上的性能:api.jquery.com/eq-selector
【解决方案3】:

使用 Slice() 函数: http://api.jquery.com/slice/

查看问题: How to select a range of elements in jQuery

$('.column').slice(0, 2).each(function() {
    $(this).val();  /* my value */
});

【讨论】:

  • Slice 可以做到这一点,但该功能非常适合选择索引范围。肯定有选择单个索引的最佳功能吗?
  • 你的意思是像 nth-child 还是 eq()?你说你想要前 3 个,也许我误解了,但这似乎是一系列索引的定义?
【解决方案4】:

您可以使用:lt(小于)选择器并通过指示索引3 下方的所有.column 元素来告诉它您想要0, 1, and 2

$("#button").on("click", function(){
  $(".column:lt(3)").each(function(){
    alert( this.value );
  });
});

演示:http://jsbin.com/icevih/edit#javascript,html

【讨论】:

    猜你喜欢
    • 2010-10-16
    • 2021-10-05
    • 1970-01-01
    • 2020-07-21
    • 2011-11-05
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多