我对jQuery插件的第一个想法

时间:2011-05-19 16:09:45

标签: jquery jquery-plugins

我一直认为jQuery中应该有.id而不是.attr('id')。

问:你如何编写一个插件,以便myObject.id返回myObject.attr('id')?

3 个答案:

答案 0 :(得分:6)

为了争论,你可以这样做。

// extend jQuery object with your id
$.fn.id = function() {
    // return the id of the first DOM element.
    return this[0].id;
}

答案 1 :(得分:4)

你已经可以做这样的事了

$(".classDiv")[0].id

或编写自己的.id()插件:)

答案 2 :(得分:1)

不确定您是否只对“id”感兴趣,我在下面提出您的问题。

考虑以下片段:

<p id="hello" another="ok" class="voila">Hello World</p>

我想用:

alert( $("#hello").another ); // -> ok
alert( $("#hello").class ); // -> voila

目前我们需要使用$ ("#hello").attr("another")因为$("#hello")[0].another无效。

相关问题