簡體   English   中英

javascript 執行兩個 if else 塊

[英]javascript executing both if else blocks

我的 Javascript function 正在執行兩個 if else 塊。 如果選中,我想在數組中添加復選框值,如果未選中則刪除值。

output 在 if 和 else 里面。 但我想運行 if 或 else 阻止。

編輯:我正在使用 php 生成動態 label 標簽。 為了便於理解,我在本示例中僅展示了一個 label 標簽。 但是每個輸入標簽的值都是從數據庫中分配的,並被包裝在 label 標簽中。

 function filterbyprotype(current) { protypes = []; document.querySelectorAll('.filterprotypes').forEach(function(ele) { console.log(ele); if (ele.checked) { current.closest('label').style.background = "var(--headercolor)"; current.closest('label').style.color = "#fff"; protypes.push(ele.value); alert("inside if"); } else { current.closest('label').style.background = "transparent"; current.closest('label').style.color = "#000"; delete protypes[ele.value]; alert("inside else"); } }); }
 <label style="padding: 6px 15px;border: 1px solid grey;border-radius: 10px;margin-right: 16px;cursor: pointer;text-transform: capitalize;"> <b><?=$filter_protype['protype']?></b> <input class="filterprotypes" type="checkbox" name="filter-protype[]" value="<?=$filter_protype['protype']?>" onchange="filterbyprotype(this)"> </label>

我只是在這個例子中展示了一個 label 標簽以便理解

那是非常不幸的,僅當輸入元素超過 1 個時才會導致您的解決方案出現問題。

document.querySelectorAll('.filterprotypes').forEach(function(ele) { ... }

這條線是有問題的,因為每次單擊其中任何一個時都會在所有輸入上觸發其中的邏輯。 此外,根本不需要此迭代,因為您已經將元素傳遞給 function ( current )。

更改后的工作解決方案:

 function filterbyprotype(current) { protypes = []; if (current.checked) { current.closest('label').style.background = "var(--headercolor)"; current.closest('label').style.color = "#fff"; protypes.push(current.value); alert("inside if"); } else { current.closest('label').style.background = "transparent"; current.closest('label').style.color = "#000"; delete protypes[current.value]; alert("inside else"); } }
 <label style="padding: 6px 15px;border: 1px solid grey;border-radius: 10px;margin-right: 16px;cursor: pointer;text-transform: capitalize;"> <b><?=$filter_protype['protype']?></b> <input class="filterprotypes" type="checkbox" name="filter-protype[]" value="<?=$filter_protype['protype']?>" onchange="filterbyprotype(this)"> </label> <label style="padding: 6px 15px;border: 1px solid grey;border-radius: 10px;margin-right: 16px;cursor: pointer;text-transform: capitalize;"> <b><?=$filter_protype['protype']?></b> <input class="filterprotypes" type="checkbox" name="filter-protype[]" value="<?=$filter_protype['protype']?>" onchange="filterbyprotype(this)"> </label>

暫無
暫無

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

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