我有以下 HTML 和 js 代碼,我試圖使用 querySelector('select:last-of-type') 選擇“計劃”下拉串列,但我無法選擇它。它始終選擇“性別”下拉選單。誰能告訴我為什么這不起作用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Welcome</title>
</head>
<body>
<table id="table" class="center">
<thead>
<th></th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Plan</th>
</thead>
<tbody id="tbody">
<tr id="newRow">
<td><input type="checkbox" id="checkbox" /></td>
<td><input type="text" id="Name" /></td>
<td><input type="number" id="Age" /></td>
<td>
<select name="Gender" id="Gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td>
<select name="Plan" id="Plan">
<option value="1 Month">Monthly</option>
<option value="3 Months">3 Months</option>
<option value="6 Months">6 Months</option>
<option value="12 Months">1 Year</option>
</select>
</td>
</tr>
</tbody>
</table>
<script>
let dropDown = document.querySelector('select:last-of-type');
console.log(dropDown)
</script>
</body>
</html>
uj5u.com熱心網友回復:
:last-of-type 將在其“兄弟”中選擇該型別的最后一個元素
https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type
#tbody td:last-of-type select 會作業,但它不是超級干凈
您可以選擇的另一個選項是查詢所有這些,然后獲取最后一個元素:
const selectEls = document.querySelectorAll('select')
const lastSelect = selectEls.length && selectEls[selectEls.length - 1]
uj5u.com熱心網友回復:
你不能像那樣使用“last of type”!
這是一個相對命令,僅用于查詢 DIRECT 父級下的特定型別的標簽(在本例中為“選擇”)。'document' 不是 'select' 的直接父級,因此您面臨此錯誤。
例如,如果您在標簽“tr”下查詢“td”,上面的代碼將起作用。(因為只有一個父級-'tr'標簽-包含標簽'td')
你也忘了關閉第二個</td>標簽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/413747.html
標籤:
上一篇:如何使用JavaScript計算購物車中產品的總價格?
下一篇:無法通過函式呼叫回傳節點元素
