获取元素eq()索引

时间:2015-04-22 09:24:10

标签: javascript jquery html

假设我在父元素中有未知数量的div元素。当我点击 div元素时,我想使用eq()打印出console.log()索引。 我不想使用任何类或ID。

HTML:

 <div id="parent">
    <div></div><!--if I click on this element eq() should be 0-->
    <div></div>
    <div></div><!--if I click on this element eq() should be 2-->
    <div></div>
    <div></div>
</div>

JS:

$(this).click(
    function(){
        console.log(eqIndex);//now this div eq is a problem
    }
);

CSS:

#parent div{
    height: 10px;
    width: 10px;
    background-color:blue;
    margin:2px;
}

DEMO

3 个答案:

答案 0 :(得分:5)

尝试将事件与element selector绑定,并通过在此对象上调用.index()来打印结果,

$('div').click(
    function(){
        console.log($(this).index());
    }
);

$('div').click(
  function() {
    $("<p>").html($(this).index()).appendTo(document.body);
  }
);
div {
  height: 10px;
  width: 10px;
  background-color: blue;
  margin: 2px;
}
<div></div>
<div></div>
<div></div><!--if I click on this element eq() should be 2-->
<div></div>
<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 1 :(得分:3)

eq() 在什么情境中是这里的问题。 index()仅返回与父项中所有元素相关的eq()。这包括脚本标签或任何其他元素类型!

在您的示例中,您可能希望将匹配范围仅限于项目及其兄弟div,然后使用该组div来确定所单击的索引:

$("div").on("click", function(){
    console.log( $(this).parent().children("div").index(this) );
});

这将避免在您编制索引的集合中包含太多元素的常见问题。

e.g。

<p>Some other sibling</p>
<div></div>
<div></div>
<div></div><!--if I click on this element eq() do you want 2 or 3? -->
<div></div>
<div></div>

如果您只想要文字eq()值,无论其他元素如何,只需使用不带参数的index()

$("div").on("click", function(){
    console.log( $(this).index() );
});

答案 2 :(得分:2)

如果要获取文档中所有div的单击div的索引,无论它们在何处,都需要使用index函数的变体:

  

如果在元素集合和DOM元素上调用.index()   或者传入jQuery对象,.index()返回一个整数   指示传递的元素相对于原​​始元素的位置   集合。

&#13;
&#13;
$(function() {
  $("div").on("click", function() {
    var index = $("div").index(this);
    /*
     * $(this).index("div") produces same result
     */
    $("#result").text("div:eq(" + index + ") was clicked");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<section>
  <div>0. (1.1)</div>
  <div>1. (1.2)</div>
  <div>2. (1.3)</div>
</section>
<section>
  <div>3. (2.1)</div>
  <div>4. (2.2)</div>
  <div>5. (2.3)</div>
</section>
<section>
  <div>6. (3.1)</div>
  <div>7. (3.2)</div>
  <div>8. (3.3)</div>
</section>
<p id="result">(click the div)</p>
&#13;
&#13;
&#13;