JQuery - $(this).attr('name')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8659523/
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-27 10:51:22  来源:igfitidea点击:

JQuery - $(this).attr('name')

jquery

提问by Nate Pet

I have a nameattribute assigned to a hyperlink.
When I do the following with jQuery link_namedoes not return anything.
Am I doing something wrong?

我有一个name分配给超链接的属性。
当我使用 jQuerylink_name执行以下操作时,不会返回任何内容。
难道我做错了什么?

$("body").delegate("a", "click", function (event) {

    var link_name = $(this).attr('name');
    alert(link_name);

回答by Rich Bradshaw

I'd use this (using newest jQuery):

我会使用这个(使用最新的 jQuery):

$("body").on("click", "a", function (event) {
    var link_name = $(this).attr('name');
    alert(link_name);
});

回答by Sparky

Quote OP:

引用 OP:

Am I doing something wrong?

难道我做错了什么?

As noted by others, your code should work if you add the missing closing brackets. });

正如其他人所指出的,如果您添加缺少的右括号,您的代码应该可以工作。 });

You also did not state which version of jQuery, however, using the latest version of 1.7, you should use on()1instead of delegate()and prop()instead of attr().

您也没有说明 jQuery 是哪个版本,但是,使用最新版本的 1.7,您应该使用1代替and代替。on()delegate()prop()attr()

$("body").on("click", "a", function (event) {
    var link_name = $(this).prop('name');
    alert(link_name);
});
  1. As of jQuery 1.7, .delegate() has been superseded by the .on() method.
  1. 从 jQuery 1.7 开始, .delegate() 已被 .on() 方法取代。