【问题标题】:jQuery: get object number in the DOM among the list of objects with the same classjQuery:在具有相同类的对象列表中获取DOM中的对象编号
【发布时间】:2015-01-25 13:27:08
【问题描述】:

假设我有 $('.mybutton').length==6 在页面上,这意味着我在页面上有六个对象,其类为 .mybutton

$('.mybutton').on('click',function(){
//one of 6 buttons was clicked
});

如果我输入 $('.mybutton') ,将按某种顺序显示六个对象。

问题是:如何获取对象的编号?

假设如果有 6 个对象并且单击了该列表的第二个对象,我需要对第 5 个对象进行一些操作。

【问题讨论】:

  • 我建议index(),但我不太确定你在问什么。
  • ...和eq()
  • 在点击事件中你可以写 var index = $.inArray( $this,$('.mybutton') );这将返回你的索引
  • 如果你的 HTML 包含明确的属性来指示元素之间的关系,你会好得多。
  • @MukeshAgarwal $('.mybutton').index(this)?

标签: javascript jquery html object


【解决方案1】:

index() 有效吗?

$('.mybutton').on('click',function(){
    console.info("button", $(this).index(), "was clicked");
});

如果元素是兄弟元素,它应该可以工作,如docsIf we omit the argument, .index() will return the position of the first element within the set of matched elements in relation to its siblings 中所述。 检查下面的示例:

$(".button").on("click", function() {
  $("#results").html("You've clicked on the element with the index " + $(this).index());
});
.button {
  padding: 5px;
  border: 1px solid grey;
  margin: 5px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <div class="button">Example 0</div>
  <div class="button">Example 1</div>
  <div class="button">Example 2</div>
  <div class="button">Example 3</div>
  <div class="button">Example 4</div>
</div>
<div><b>Results:</b>
</div>
<div id="results"></div>

如果由于某些奇怪的原因不起作用,快速解决方案将是.....

(请注意,根据标准/性能,这可能不是最佳解决方案)

$('.mybutton').each(function(i) {
    $(this).on('click',function(){
        console.info("button", i, "was clicked");
    });
});

但如果 index 真的不起作用,您应该将类​​、id、数据参数(任何允许我们区分项目的任何内容)添加到您要修改的按钮。

例如,假设您向第 5 个按钮添加一个类 special-modifier,您会执行以下操作:

$('.mybutton').on('click',function(){
    if($(this).is(".special-modifier")) {
        console.info("special modifier button was clicked");
    }
});

【讨论】:

  • 不,那行不通——.index() 基于所涉及的 jQuery 对象工作,所以当你用$(this) 创建一个新对象时,它们的索引都为零。 (不过,第二个代码示例可能会起作用。)
  • 嗯@Pointy 这实际上不是真的,它似乎使用 HTML 兄弟而不是“涉及的 jQuery 对象”-我在jsfiddle.net/bbk2tjv5 做了一个示例来演示这一点-如果元素都是兄弟那么索引技术将起作用。如果您查看api.jquery.com/index 的文档,您会发现If we omit the argument, .index() will return the position of the first element within the set of matched elements in relation to its siblings - 因此在按钮上调用.index() 将起作用,无论它被调用的上下文如何 - 只要它们都是兄弟姐妹:)
  • 不是问题@Pointy,嘿,如果你有这个“问题”,其他人将来可能会想到同样的事情,我会相应地更新我的答案:) 谢谢!跨度>
猜你喜欢
  • 2021-08-11
  • 2021-05-31
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多