2011-04-26 64 views
2

如何获得对象的ID,我知道ID是HOLA,但我需要在运行过程中得到它如何获取对象的ID?

alert($('#hola').id); 

的想法是这样的:

<script> 

    (function ($) { 

    $.fn.hello = function(msg) { 
     alert('message ' + msg); 
     alert('is from ' + this.id); // this.id doesn't work 
    }; 

    })(jQuery); 


    $('#hola').hello('yo'); 

</script> 
+1

在一个jQuery插件中,'this'是指代表所选元素的jQuery对象。在这种情况下,使用'this.attr('id')'作为@Joachim发布,可能是最简单的方法(和'$('#hola').id'不能用btw)。 – 2011-04-26 11:58:03

回答

10

使用attr()读取属性:

alert($('#hola').attr('id')); 
+1

快37秒! – 2011-04-26 11:57:26

5

你可以把它读作atttibute:

alert($('#hola').attr('id')); 
6

最有效的方法是:

this[0].id 

this.attr("id")需要较长时间才能达到同样的事情,因为很多的检查是由不同codepaths基于传递的参数紧随其后。根据您调用该功能的频率,可能存在显着差异,例如,处理速度较慢的移动浏览器。

您可以阅读更多关于此here

+1

+1,但必须检查'this'是否包含元素。 – 2011-04-26 12:08:17

+1

@Felix:是的,这很好指出。当this [0]没有定义或者不是一个对象时,'typeof this [0] ==“object”&& this [0] .id'应该足以防止错误。 – 2011-04-26 12:10:20

相关问题