简体   繁体   English

为什么此复选框缺少“选中”属性?

[英]Why is this checkbox missing the “checked” property?

In a component I'm writing I want to examine the "checked" property of an element. 在我正在编写的组件中,我想检查元素的“检查”属性。 Unfortunately, it appears that the element doesn't contain the "checked" property, at least not the way I set things up. 不幸的是,该元素似乎不包含“ checked”属性,至少不包含我的设置方式。

Here's the JS snippet: 这是JS代码段:

var submenus  = document.querySelectorAll( ".hbm-panel-item-label" );
for ( var label of submenus ) {
  // console.log( "label.for = " + label.getAttribute( "for" ) );

  label.addEventListener( "click", function() {
    var label_for = this.getAttribute( "for" ); 
    // console.log( label_for + " was clicked." );

    var checkboxes = document.querySelectorAll( ".hbm-panel-item-checkbox" );
    for ( var cb of checkboxes ) {
      console.debug( cb );

      if ( cb.getAttribute( "name" ) === label_for ) {
        console.log( label_for + " has attribute 'checked': " + cb.hasAttribute( "checked" ) );
        console.log( label_for + " is " + cb.getAttribute( "checked" ) );  
      }
    }
  });
}

...and here's the result: ...结果如下:

Firefox控制台输出

When I open the properties for that element, I do see a checked property with a value of "false": 当我打开该元素的属性时,我确实看到了一个值为“ false”的选中属性:

在此处输入图片说明

Apologies in advance, I'm a JS rookie. 提前道歉,我是JS新手。 I get the feeling this is something simple. 我觉得这很简单。 I also get the feeling that if I used jQuery this would take about three lines of code... 我也有一种感觉,如果我使用jQuery,这大约需要三行代码...

A property is in the DOM, an attribute is in the HTML that is parsed into the DOM. 属性位于DOM中,属性位于HTML中,该属性已解析为DOM。 The HTML for the checkbox has no attribute 'checked', but the checkbox has a property 'checked'. 复选框的HTML没有属性“已选中”,但是复选框具有“已选中”属性。 You'll probably just need to check 您可能只需要检查一下

cb.checked

instead of looking for the attribute. 而不是寻找属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM