如何获取对象的id,我知道id是hola,但我需要在运行时获取它
alert($('#hola').id);
Run Code Online (Sandbox Code Playgroud)
这个想法是这样的:
<script>
(function ($) {
$.fn.hello = function(msg) {
alert('message ' + msg);
alert('is from ' + this.id); // this.id doesn't work
};
})(jQuery);
$('#hola').hello('yo');
</script>
Run Code Online (Sandbox Code Playgroud)
最有效的方法是:
this[0].id
Run Code Online (Sandbox Code Playgroud)
this.attr("id")
需要更长时间才能实现相同的功能,因为会进行许多检查,并根据传递的参数遵循不同的代码路径.根据您调用该功能的频率,例如,处理器速度较慢的移动浏览器可能存在显着差异.
你可以在这里阅读更多相关信息.