jQuery:获取 title 和 href 值作为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14315193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:27:08  来源:igfitidea点击:

jQuery: Get title and href values as variables

jqueryvariables

提问by Meek

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:

我有一个带有标题和 href 值的链接列表。我希望能够单独获得这些值,但我总是获得第一个链接的值。这是为什么? 在这里查看我的小提琴。如您所见 - 单击任何链接时,您始终会从第一个链接获取值。我想设置这些变量是不够的:

var title = $('.mg_phones').attr('title');
var url = $('.mg_phones').attr('href');

Any ideas?

有任何想法吗?

回答by johankj

You have to refer to the clicked element:

你必须参考被点击的元素:

var title = $(this).attr('title');
var url = $(this).attr('href');

回答by hjpotter92

You need to change the code to this:

您需要将代码更改为:

var title = $(this).attr('title').toLowerCase();
var url = $(this).attr('href');

回答by codingbiz

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.

使用$(this)来代替。问题是这$('.mg_phones')是一个包含该类的所有元素的数组,访问$('.mg_phones').attr(...)将选择第一个元素,因为它不知道您想要哪个元素。

But $(this)refers to the currently clicked item in this context.

$(this)在此上下文中指的是当前单击的项目。

$('.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);
 }