没有获得点击的href标记的索引值

时间:2017-03-30 09:11:55

标签: javascript jquery html

我有以下html

HTML code for testing purposes (do not submit uncommented):
<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>

我的JS

$('a[id^=mm]').on('click', function () {
alert("test")
var as = document.body.getElementsByTagName("a");
alert("test")
for(var i=0; i < as.length;i++) {
  as[i].onClick = function(){
          alert(i);
  }
   }  
});

警报未给我点击链接的索引。我怎样才能获得索引?

2 个答案:

答案 0 :(得分:1)

将jquery与index()函数

一起使用

&#13;
&#13;
$('body').on('click','a[id^=mm]', function () {
console.log($(this).index()/2)

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML code for testing purposes (do not submit uncommented):

<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试以下方法:

&#13;
&#13;
$('a[id^=mm]').on('click', function () {
    var nodeList = Array.prototype.slice.call(document.body.getElementsByTagName("a"));
    var index = nodeList.indexOf($(this)[0]);
    alert('You have clicked: '+index)
}); 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In my life, I used the following web search engines:<br/>
<a href="#test" id="mmYahooId">Yahoo!</a><br/>
<a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
<a href="#test" id="mmgooId">Google</a><br/>
&#13;
&#13;
&#13;