javascript - 获取元素 eq() 索引

标签 javascript jquery html

假设我在父元素中有未知数量的 div 元素。当我点击 child div 元素时,我想使用 console.log() 打印出它的 eq() 索引。 我不想使用任何类或 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

最佳答案

尝试用元素选择器绑定(bind)事件,并通过调用.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>

关于javascript - 获取元素 eq() 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793109/

相关文章:

php - Jquery Onclick 更改隐藏参数并提交

javascript - 如何获取由javascript创建的动态表的css属性?

javascript - 过滤具有不同输入的数据属性

php - 从表中获取数据到 php

javascript - 在 Array.prototype.map 中返回一个迭代步骤

javascript - 模态对话框 (showModalDialog()) 在 IE9 中无法正常运行

javascript - MeanJS - 将 Angular 集成到 index.html 文件中

javascript - 从 JSON 对象中删除空格,但不在引号内

javascript - 为什么这行 Jquery selectiong ALL div's with the class=rule-name?

javascript - 知道所有其他就绪回调何时完成