我有以下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);
}
}
});
警报未给我点击链接的索引。我怎样才能获得索引?
答案 0 :(得分:1)
将jquery与index()
函数
$('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;
答案 1 :(得分:1)
尝试以下方法:
$('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;