简体   繁体   English

为什么第一个代码有效而第二个代码无效?

[英]why does the first code work and the second doesn't work?

when I put div.main as a separated condition the code doesn't work 当我将div.main作为单独的条件时,代码不起作用

<div class="user-panel main"> 
    <input type="text" name="login"> 
</div>




 document.querySelector("div.user-panel.main input[name='login']").style.backgroundColor = "red"; // this code works
 document.querySelector("div.user-panel  div.main input[name='login']").style.backgroundColor = "red"; // this code doesn't work

When your selectors are combined with a space - a descendant combinator - it's called a descendant selector. 当选择器与一个空格( 后代组合器) 组合在一起时 ,它称为后代选择器。 So 所以

document.querySelector("div.user-panel  div.main input[name='login']")

is looking for a input[name='login'] inside a div.main inside a div.user-panel . 正在div.user-panel内的div.main内寻找input[name='login']

Since in your html it's just a single div with 2 classes, this selector doesn't find anything. 由于在您的html中,它只是一个具有2个类的div,因此此选择器无法找到任何内容。

It would work, however, if your html was looking like this: 但是,如果您的html看起来像这样,它将起作用:

<div class="user-panel">
    <div class="main">
        <input type="text" name="login"> 
    </div>
</div>

A space in a query selector denotes one element is inside another. 查询选择器中的空格表示一个元素在另一个元素内部。 The second line is looking for input[name='login'] contained in div.main , which is contained within another div ( div.user-panel ). 第二行正在查找div.main包含的input[name='login'] ,该输入包含在另一个div( div.user-panel )中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript表单验证:为什么第一种有效,但第二种无效? - JavaScript form validation: Why does the first work but the second doesn't? 为什么我的第一个snippit工作,但我的第二个没有? - Why does my first snippit work, but my second doesn't? 谁能解释这两个代码之间的区别? 又为什么第二个有效而第一个无效呢? - Can anyone explain the difference between those two codes? And why does the second one work and the first doesn't? 有人知道为什么第一个 onClick 事件不能正常工作,而第二个却能正常工作? - Someone knows why the first onClick event doesn't work correctly and the second does? 第一次单击元素不起作用,第二次单击起作用 - First click of element doesn't work, second click does 为什么这段代码在jsfiddle中不起作用 - Why does this code doesn't work in jsfiddle 为什么第一个程序起作用,而第二个程序却不起作用? - Why does the first program work but not the second? 为什么onanimationend在我的代码中不起作用,但addEventListener(“animationend”)呢? - Why doesn't onanimationend work in my code, but addEventListener(“animationend”) does? 为什么此代码在FireFox和IE中不能使用,而在Chrome中不能使用? - Why Doesn't This Code Work in FireFox and IE but does in Chrome? 它在第一次点击时不起作用,但在第二次点击时起作用。 如何解决? - It doesn't work on the first click, but does on the second one. How to fix that?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM