获取特定标记的索引

时间:2016-01-11 13:30:13

标签: javascript indexing

如何在不计算textareas索引的情况下获取单击段落的索引?

html代码:

<div class="story">
<p>index is 0, that's ok</p>
<textarea></textarea>
<p>index is 2, should be 1</p>
<textarea></textarea>
<p>index is 4, should be 2</p>
</div>

JS:

$(".story > p").click(function() {
    var a = $(this).index();
    alert (a);
});

3 个答案:

答案 0 :(得分:3)

$.index(selector)表示要在其中查找元素的jQuery集合的选择器。

$(".story > p").click(function() {
    var a = $(this).index("p");
    alert (a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="story">
<p>index is 0, that's ok</p>
<textarea></textarea>
<p>index is 2, should be 1</p>
<textarea></textarea>
<p>index is 4, should be 2</p>
</div>

答案 1 :(得分:0)

以原生方式:

&#13;
&#13;
var els = document.querySelectorAll('.story > p');

Array.prototype.slice.call(els).forEach(function(el, i) {
  el.addEventListener('click', function() {
    alert(i);  // in this case, alert 0, 1, 2
  });
})
&#13;
<div class="story">
<p>index is 0, that's ok</p>
<textarea></textarea>
<p>index is 2, should be 1</p>
<textarea></textarea>
<p>index is 4, should be 2</p>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var pTags = document.querySelectorAll('.story p');

function printIndex(i) {
  console.log(i);
}

for (var i = 0; i < pTags.length; i++) {
  pTags[i].addEventListener("click", printIndex.bind(this, i));
}