簡體   English   中英

為什么第一個代碼有效而第二個代碼無效?

[英]why does the first code work and the second 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

當選擇器與一個空格( 后代組合器) 組合在一起時 ,它稱為后代選擇器。 所以

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

正在div.user-panel內的div.main內尋找input[name='login']

由於在您的html中,它只是一個具有2個類的div,因此此選擇器無法找到任何內容。

但是,如果您的html看起來像這樣,它將起作用:

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

查詢選擇器中的空格表示一個元素在另一個元素內部。 第二行正在查找div.main包含的input[name='login'] ,該輸入包含在另一個div( div.user-panel )中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM