HTML
<div>
<a href=''> First </a>
</div>
<div>
<div>
<a href=''> Second </a>
</div>
</div>
<a href=''>Third</a>
脚本
$(document).ready(function(){
$('a').click(function(){
// find next a element
//var next = $(this).next('a');
//console.log(next.text());
});
});
小提琴:https://jsfiddle.net/usyu30t6/
我希望如果我点击第一个a
元素,它会给我下一个a
元素的文本。如果我点击第二个a
元素,它会给我下一个元素,依此类推。有可能吗?
答案 0 :(得分:2)
您也可以将点击处理程序存储在变量中并像这样访问它们
$(document).ready(function () {
var allAs = $('a').click(function (e) { // <--- List of anchor tags
e.preventDefault();
var i = allAs.index(this) + 1; // <--- get next Index
alert(allAs.eq(i).text()); // <--- get next anchor tag's text
});
});
完整演示:
$(document).ready(function() {
var allAs = $('a').click(function(e) {
e.preventDefault();
var i = allAs.index(this) + 1;
alert(allAs.eq(i).text());
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href=''> First </a>
</div>
<div>
<div>
<a href=''> Second </a>
</div>
</div>
<a href=''>Third</a>
&#13;
答案 1 :(得分:1)
$('a').click(function(){
var currentIndex = $('body a').index($(this))+1;
var text = $('body a:eq('+currentIndex+')').text();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<a href='javascript:void(0)'> First </a>
</div>
<div>
<div>
<a href='javascript:void(0)'> Second </a>
</div>
</div>
<a href='javascript:void(0)'>Third</a>
答案 2 :(得分:1)
试试这个 -
$(document).ready(function(){
var allAnchorElements = $("a");
allAnchorElements.click(function(){
// find the index of current element
var index = allAnchorElements.index($(this));
// find the next element
var next = allAnchorElements.eq(index+1);
// text of next element
console.log(next.text());
});
});
这是一个展示这个想法的小提琴 - https://jsfiddle.net/callicoder/qpnt0rh6/