Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 为什么';t此工作:$(“body div button”)[0].css_Jquery - Fatal编程技术网

Jquery 为什么';t此工作:$(“body div button”)[0].css

Jquery 为什么';t此工作:$(“body div button”)[0].css,jquery,Jquery,鉴于此HTML: <div id="flashcard-001" class="flashcard"> <div class="question">What color is the sky?</div> <div class="answer">blue</div> <button class="show">Show</button> <button class="hide"

鉴于此HTML:

<div id="flashcard-001" class="flashcard">
    <div class="question">What color is the sky?</div>
    <div class="answer">blue</div>
    <button class="show">Show</button>
    <button class="hide">Hide</button>
</div>
那么,为什么这不起作用(第一个按钮没有按预期变成红色):


当您在jQuery对象之后指定[0]时,您正在访问直接DOM元素,并且DOM元素没有定义“css”方法()。css方法适用于jQuery对象,因为它是在jQuery.prototype中定义的,并且所有jQuery对象都继承该方法,这就是为什么:

$('body').css('background','red')

有效,并且$('body')[0]。css将抛出一个错误。

如果您这样做:

$("body div button")[0].cssText = 'background-color', 'red';
这应该行得通

当您使用[0]时,您看到的是DOM对象,因此此时您不能使用jQuery助手函数,而直接转到DOM属性。

请改用:

$("body div button:first").css(...

正如其他人已经指出的,当您使用括号语法时,您访问的是实际的DOM元素,而不是jQuery对象

试一试

甚至更好

$("body div button:first").css('background-color', 'red');

你可能想看看你是否能对你所问的一半的问题给出一个最好的答案。52%实际上是大约一半:-)但是你是对的,我经常回去,尝试在老问题上提高我52%的分数,因为我真的很欣赏答案,但在许多问题上,确实没有答案,并标记一个,因为答案可能会给某人打分,但会误导找到问题的人,应该阅读所有答案,以了解人们的想法由于确实没有正确的答案,我几乎总是对我认为有见地或在某种程度上有用的答案打分。谁对此投了反对票?这是完全正确的答案。omg对第一个提供公认答案的人投了反对票!??我想你的意思是
$(“body div按钮”)[0].cssText+='背景色:红色'取决于他是替换还是附加到css,但你可能认为它应该是+=。
$("body div button")[0].cssText = 'background-color', 'red';
$("body div button:first").css(...
$("body div button").eq(0).css('background-color', 'red');
$("body div button:first").css('background-color', 'red');