Javascript Jquery each 和 attr 函数

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

Jquery each and attr functions

javascriptjqueryhtml

提问by kralco626

I have this html:

我有这个 html:

<input id="testme" test="something"/><label test="something2"></label>

and this js

而这个js

$("[test]").each(alert($(this).attr("test")));

demoed here:

在这里演示:

jsfidde

杰菲德

I would think the alert would give me "something"and then "something2". But it does nothing!

我认为警报会给我"something",然后"something2"。但它什么都不做!

What is going on?

到底是怎么回事?

回答by Josiah Ruddell

You are alerting the wrong thing. The eachsimply returns the collection/jQuery. You would need to alert inside the each callback to alert the values of the custom attribute. Also. Please use the data-prefix when assigning [custom attributes][1] for better standards compliance.

你在警告错误的事情。在each简单地返回集合/ jQuery的。您需要在每个回调中发出警报以提醒自定义属性的值。还。请data-在分配 [自定义属性][1] 时使用前缀以更好地符合标准。

$(".classname").each(function(){
    alert($(this).attr("classname"));
});

回答by Nick Craver

.each()takes a function, it should look like this instead:

.each()接受一个函数,它应该看起来像这样:

$("[test]").each(function() {
  alert($(this).attr("test"));
});

You can test it out here.

你可以在这里测试一下