$("left_menu_bar").innerHTML = "You clicked me!";
但是当我用该代码init调用函数时,div根本没有改变。
答案 0 :(得分:16)
这样做:
// referencing by id
$("#left_menu_bar").html("You clicked me!");
// referencing by class name ( will apply to all div's with this class )
$(".left_menu_bar").html("You clicked me!");
答案 1 :(得分:4)
jQuery总是返回一个jQuery 集合 - 而不是一个DOM元素。为了直接访问DOM属性,您需要从集合中检索元素:
$(".left_menu_bar").first().innerHTML = "You clicked me!";
然而,这不是很方便,而helmus的回答描述了通常的事情。
答案 2 :(得分:2)
由于left_menu_bar不是一个元素,你不能那样选择它。
如果是元素的ID,请尝试:
$("#left_menu_bar").html("You clicked me!");
如果它是元素的类,请尝试:
$(".left_menu_bar").html("You clicked me!");
答案 3 :(得分:1)
您正在尝试将一些文本分配给名为innerHTML
的属性,该对象没有名为innerHTML
的属性。
jQuery中的$
函数不返回DOM元素。它返回一个jQuery对象,它提供了在特定DOM元素上执行所有精彩jQuery函数的能力。
jQuery对象公开的一个函数是.get()
,它将返回它包含的一个元素。
所以在你的情况下,你可以这样做:
// 0 means it will return the first element in the jQuery object
$("left_menu_bar").get(0).innerHTML = "You clicked me!";
或者@hemus在他的回答中说,你可以使用jQuery提供的.html()
函数来设置内部实际使用innerHTML的内容。