我需要將單選按鈕設定為我通過 url 傳遞的值。
function filterCategory(ads) {
let categories = Array.from(new Set(ads.map(ann => ann.category)));
let rowCategoryRadio = document.querySelector('#row-category-radio');
categories.forEach((cat, i) => {
let input = document.createElement('div');
input.classList.add('form-check');
input.innerHTML = `
<input type="radio" name="category-filter" id="flexRadioDefault${i}" data-filter="${cat}">
<label for="flexRadioDefault${i}">
${cat}
</label>
`
rowCategoryRadio.appendChild(input);
})
}
<div class="row" id="row-category-radio">
<div class="form-check">
<input class="form-check-input filter-category" type="radio" name="category-filter" id="flexRadioDefault1" data-filter="all" checked>
<label class="form-check-label" for="flexRadioDefault1">
All categories
</label>
</div>
</div>
要將單選按鈕設定為我步驟的值,我撰寫了以下代碼,只是我得到了 selected null的值
let url_string = window.location.href;
let url2 = new URL(url_string);
let name_url = url2.searchParams.get("name");
let radios = document.querySelector('.filter-category');
let selected = radios.querySelector(`[data-filter="${name_url}"]`);
selected.checked = true;;
console.log(selected);
任何人都可以幫助我嗎?
uj5u.com熱心網友回復:
radios.querySelector()搜索嵌套在radios與選擇器匹配的元素。但是該data-filter屬性在radios元素本身上,而不是嵌套元素上。
您想將它們放入單個查詢選擇器中。
let selected = document.querySelector(`.filter-category[data-filter="${name_url}"]`)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487201.html
標籤:javascript
