【问题标题】:jquery get current number of childjquery获取当前孩子的数量
【发布时间】:2014-09-22 10:23:06
【问题描述】:
<div id="sample">
  <h3>headline 1</h3>
  <h3>headline 2</h3>
  <h3>headline 3</h3>
</div>

现在如何确定点击的 h3 子元素并使用 jquery 处理?

var id = $("h3").index();

这不是吗?

【问题讨论】:

标签: jquery tags


【解决方案1】:

在点击处理程序中,您必须引用$(this) 来引用被点击的元素。试试看

$("h3").on("click",function(){


  alert($(this).index());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sample">
  <h3>headline 1</h3>
  <h3>headline 2</h3>
  <h3>headline 3</h3>
</div>

【讨论】:

    【解决方案2】:

    在索引函数内部传递this

    $("h3").click(function(){
     var id = $("h3").index(this);
    })
    

    【讨论】:

      【解决方案3】:

      试试

      $("h3").click(function(event){
        alert( $(this).index() + 1);
      });
      

      DEMO

      【讨论】:

        【解决方案4】:

        你需要在h3元素上写点击事件:

        $("h3").click(function() {
          var index= $(this).index();
          alert(index);
        });
        

        Working Demo

        【讨论】:

        • 无论我点击哪个孩子,这只会返回 0
        猜你喜欢
        • 1970-01-01
        • 2011-01-11
        • 2021-06-09
        • 2018-03-06
        • 2018-06-13
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多