jQuery: Get title and href values as variables

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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);  } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!