Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Jquery获取特定标记的索引_Jquery - Fatal编程技术网

使用Jquery获取特定标记的索引

使用Jquery获取特定标记的索引,jquery,Jquery,有没有一种方法可以只索引父元素中的特定元素?例如: $('h4').click(function(){ alert($('div h4').index('h4')); }); <div> <p>do not include in indexing</p> <p>do not include in indexing</p> <p>do not include in indexing</p> &l

有没有一种方法可以只索引父元素中的特定元素?例如:

$('h4').click(function(){

   alert($('div h4').index('h4'));

});

<div>
 <p>do not include in indexing</p>
 <p>do not include in indexing</p>
 <p>do not include in indexing</p>
 <p>do not include in indexing</p>
<h4>Tag I want to include in index</h4>
<h4>Tag I want to include in index</h4>
</div>
$('h4')。单击(函数(){
警报($('div h4')。索引('h4'));
});
不包括在索引中

不包括在索引中

不包括在索引中

不包括在索引中

我想包含在索引中的标记 我想包含在索引中的标记
我想从中得到的是与我单击的h4标记对应的0或1警报

使用jquery可以做到这一点吗

更新 感谢所有的答案,你们提供的大部分都是有用的,但在工作实践中,它似乎不起作用。我想我在我的页面的其他地方有问题

无论如何谢谢你试试这个

$('h4').click(function(){    
   alert($('div h4').index(this));    
});
小提琴示例:

根据:

如果我们使用字符串作为.index()方法的参数,它将被解释为jQuery选择器字符串。对象的匹配元素中与此选择器匹配的第一个元素位于


所以你可以做:

$('h4').click(function(){    
    var idx = $(this).index('h4');
    alert(idx);
});​

使用此测试HTML:

  <div id="main">
      <p>do not include in indexing</p>
      <p>do not include in indexing</p>
      <p>do not include in indexing</p>
      <p>do not include in indexing</p>
      <h4>Tag I want to include in index</h4>
      <h4>Tag I want to include in index</h4>
   </div>     
   <div id="test"></div>
这将向我添加的testdiv元素追加0或1


jsiddle:

您可以通过伪类选择第一个和最后一个:last:first谢谢,但是nah不适合,因为我需要switch语句的返回值代码已经忽略了
标记。这只是你然后寻找任何
标签的索引,而不是点击的标签。也可以被写入。索引(这)就像索引文档中的第一个例子是的,小提琴的例子很好,它只是在我的实际页面中,有所有其他的代码,它给所有其他标签计数,然后给div一个id,然后像这样尝试$(#mydiv').find('h4').index(this)
  <div id="main">
      <p>do not include in indexing</p>
      <p>do not include in indexing</p>
      <p>do not include in indexing</p>
      <p>do not include in indexing</p>
      <h4>Tag I want to include in index</h4>
      <h4>Tag I want to include in index</h4>
   </div>     
   <div id="test"></div>
$('h4').click(function() {
  var index1 = $(this).index("h4");
  $("#test").append(index1);
});​