![](/img/trans.png)
[英]JavaScript form validation: Why does the first work but the second doesn't?
[英]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.