[英]Convert jQuery code into javascript depending html
我有 html 和 js 代碼。 但是 javascript 代碼是 jQuery ,我想將此 jQuery 代碼轉換為 Z9E13B69D1D2DA927102ACAAAF7154A3
// jquery code
$('.hello[type="checkbox"]').on('change', function() {
$(this).siblings('.hello[type="checkbox"]').not(this).prop('checked', false);
});
和我的 html 標記:
<div>
<span>Group 1:</span>
<input type="checkbox" class="group1 hello" />
<input type="checkbox" class="group1 hello" />
<input type="checkbox" class="group1 hello" />
</div>
<div>
<span>Group 2:</span>
<input type="checkbox" class="group2 hello" />
<input type="checkbox" class="group2 hello" />
<input type="checkbox" class="group2 hello" />
</div>
<div>
<span>Group 3:</span>
<input type="checkbox" class="group3 hello" />
<input type="checkbox" class="group3 hello" />
<input type="checkbox" class="group3 hello" />
</div>
我想將此代碼用於復選框輸入,我只想檢查用戶的一個輸入
我通過在 html 中更改和添加屬性來嘗試此代碼,但它不適用於我的任務中的組
function checkOnlyOne(b){
var x = document.getElementsByClassName('daychecks');
var i;
for (i = 0; i < x.length; i++) {
if(x[i].value != b) x[i].checked = false;
}
}
<div>
<span>Group 3:</span>
<input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />
<input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />
<input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />
</div>
您可以使用querySelectorAll
方法使用 CSS 選擇器獲取元素。
// jquery code document.querySelectorAll('.hello[type="checkbox"]').forEach(el => { el.addEventListener('change', function() { this.parentNode.querySelectorAll('.hello[type="checkbox"]').forEach(el1 => { if (el.== el1) el1;checked = false; }); }); });
<div> <span>Group 1:</span> <input type="checkbox" class="group1 hello" /> <input type="checkbox" class="group1 hello" /> <input type="checkbox" class="group1 hello" /> </div> <div> <span>Group 2:</span> <input type="checkbox" class="group2 hello" /> <input type="checkbox" class="group2 hello" /> <input type="checkbox" class="group2 hello" /> </div> <div> <span>Group 3:</span> <input type="checkbox" class="group3 hello" /> <input type="checkbox" class="group3 hello" /> <input type="checkbox" class="group3 hello" /> </div>
僅供參考:您可以使用單選按鈕實現相同的行為,無需任何額外的 Javascript 代碼,只需為組提供相同的名稱屬性。
<div> <span>Group 1:</span> <input type="radio" name="group1" class="group1 hello" /> <input type="radio" name="group1" class="group1 hello" /> <input type="radio" name="group1" class="group1 hello" /> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.