Javascript 如何获取对象的id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5789902/
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
How to get the object's id?
提问by Hao
How to get the id on an object, i know the id is hola, but i need to get it during runtime
如何获取对象的 id,我知道 id 是hola,但我需要在运行时获取它
alert($('#hola').id);
The idea is this:
这个想法是这样的:
<script>
(function ($) {
$.fn.hello = function(msg) {
alert('message ' + msg);
alert('is from ' + this.id); // this.id doesn't work
};
})(jQuery);
$('#hola').hello('yo');
</script>
回答by Andy E
The most efficient approach would be:
最有效的方法是:
this[0].id
this.attr("id")
takes longer to achieve the same thing because many checks are made and different codepaths are followed based on the parameter passed. Depending on how often you call the function, there could be a significant difference on, say, a mobile browser with a slow processor.
this.attr("id")
需要更长的时间才能实现相同的目标,因为进行了许多检查,并且根据传递的参数遵循不同的代码路径。根据您调用该函数的频率,例如在处理器速度较慢的移动浏览器上可能存在显着差异。
You can read more about this here.
您可以在此处阅读更多相关信息。
回答by Shadow Wizard is Ear For You
You can read it as atttibute:
您可以将其阅读为 atttibute:
alert($('#hola').attr('id'));