【问题标题】:How do I convert this jquery to pure javascript?如何将此 jquery 转换为纯 javascript?
【发布时间】:2020-07-24 04:50:09
【问题描述】:

您好,如果可能的话,我想将以下内容转换为纯 JS。

我的最终目标是显示 var “bar”,如果选择了带有 id 的复选框(“checkbox1”、“checkbox2”、“checkbox3”)+ 显示相应的 id (“item1”、“item2”、“item3”) .

$('input:checkbox').change(function () {
    if ($(this).is(':checked')) {
        switch (this.id){
            case 'checkbox1':
                bar.show();
                item1.show();
                break;
            case 'checkbox2':
                bar.show();
                item2.show();
                break;
            case 'checkbox3':
                bar.show();
                item3.show();
                break;
            default:
                bar.hide();
        }
    } else {
        bar.hide();
    }
});

我怎样才能简单地做到这一点?

【问题讨论】:

  • 也添加 HTML。

标签: javascript jquery checkbox checked oncheckedchanged


【解决方案1】:

试试这个代码示例。

const ids = ["item1", "item2", "item3"]

document.addEventListener("change", function(event) {
  if (event.target.matches('input[type="checkbox"]')) {
    const checkboxes = document.querySelectorAll('input[type="checkbox"]')
    let checked = []
    
    checkboxes.forEach(function (cb) {
      if (cb.checked) checked.push(cb)
    })
      
    const checkedIds = checked.map(cb => cb.id)
    
    if (isSubArray(ids, checkedIds)) {
      document.querySelector("#var").style.display = "block"
    } else  {
      document.querySelector("#var").style.display = "none"
    }
    
    document.querySelector("#cb-ids").innerHTML = checkedIds
  }
})

function isSubArray(arr1, arr2) {
  return arr1.every( el => arr2.includes(el))
}
<p id="var" style="display: none">var</p>

<p id="cb-ids"></p>

<label for="item1"> 
  <input id="item1" type="checkbox" />
   Item 1 
<label/>
<label for="item2"> 
  <input id="item2" type="checkbox" />
   Item 2 
<label/>
<label for="item3"> 
  <input id="item3" type="checkbox" />
   Item 3
<label/>
<label for="item4"> 
  <input id="item4" type="checkbox" />
   Item 4
<label/>

【讨论】:

    【解决方案2】:
    1. 要选择 HTML 元素,您可以使用 document 类方法(例如 document.getElementsByTagName)。
    2. jQuery's documentationshow()hide() 中所写,实际上修改了HTML 元素的display 属性。

    【讨论】:

    • 感谢您的回答!我确实想摆脱 jQuery 并想用纯 JS 编写所有东西。 css伪类有可能吗? if/else 语句会是什么样子?
    猜你喜欢
    • 2020-05-07
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2016-01-16
    • 2019-05-26
    相关资源
    最近更新 更多