可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a list of links with a title and a href value. I would like to be able to get these values seperately, but I always get the first link's values. Why is that? See my fiddle here. As you can see - when clicking a any of the link, you always get the values from the first link. I guess setting these variables isn't sufficient:
var title = $('.mg_phones').attr('title'); var url = $('.mg_phones').attr('href');
Any ideas?
回答1:
You have to refer to the clicked element:
var title = $(this).attr('title'); var url = $(this).attr('href');
回答2:
You need to change the code to this:
var title = $(this).attr('title').toLowerCase(); var url = $(this).attr('href');
回答3:
Use $(this)
instead. The issue was that $('.mg_phones')
is an array of all elements with that class and accessing $('.mg_phones').attr(...)
would pick the first element as it doesn't know which of them you want.
But $(this)
refers to the currently clicked item in this context.
$('.mg_phones').click(function (event) { event.preventDefault(); var title = $(this).attr('title').toLowerCase(); //this changed var url = $(this).attr('href'); //this changed if (title.length != 0) { $('#test').text(title + ": " + url); }