jQuery没有找到元素或其属性

时间:2012-07-16 18:18:12

标签: javascript jquery getelementbyid

我有这个:

<h1 id="test" class="test">

并在脚本部分中:

alert($('#test').id)
alert($('.test').id)

jQuery肯定是加载的。但是我在警报框中得到 undefined - 两次都是。如果我使用常规的 getElementById ,它可以工作并显示 test

到底有什么不对(和我一起)

这是一个例子http://jsfiddle.net/tF6bd/

2 个答案:

答案 0 :(得分:4)

变化:

alert($('#test').id)

为:

alert($('#test').attr('id'))

或:

alert($('#test')[0].id)

对于jQuery对象,您应该使用attr()方法。

答案 1 :(得分:0)

您可以使用attrprop,区别在于attr如果尚未设置属性则返回undefined

<强>实施例
alert($('test').attr('id'));
alert($('test').prop('id'));

演示

<强>参考