警告$(this)时如何获取HTML元素而不是[object Object]

时间:2011-12-01 14:35:13

标签: jquery

我正在尝试使用console.log($(this))查看是否使用jQuery选择了正确的元素,然后我得到[object Object]

为什么会这样,我如何获得元素的名称?

4 个答案:

答案 0 :(得分:2)

这是因为console.log函数需要记录文本,并且您正在传递实例。该函数不会将您的实例单独解析为idname或任何其他属性。您可以将idname属性传递给日志函数tho ..

尝试:

console.log($('selector').attr("id"))

console.log($('selector').attr("name"))

答案 1 :(得分:1)

jQuery对象是多个数组,如果你想拥有对象本身,可以将它用作数组,如:

console.log($('selector')[0])

获取名称:

console.log($('selector')[0].name)
console.log($('selector').prop("name"))

获取标记名:

console.log( $('#test')[0].tagName );

答案 2 :(得分:1)

你得到[object Object],因为它就是它 - jQuery对象。

要使用attr()或jQuery 1.7+获取ID或任何其他属性,请使用prop()

alert($("#myElement").attr("id"));
alert($("#myElement").attr("name"));

// The same in jQ1.7:
alert($("#myElement").prop("id"));
alert($("#myElement").prop("name"));

答案 3 :(得分:0)

使用firebug可以在将对象转储到控制台时看到对象的结构。例如:

console.log($('#logo'))

返回:

 Object { 0=div#logo, length=1, jquery="1.2.6"}

如果我点击它,Firebug将我带到DOM面板,左边有一个带“加号”的“0”,可以让你探索对象的内部结构。