【问题标题】:Why clicking on checkbox does not add the attribute checked='checked' [closed]为什么单击复选框不会添加属性checked='checked' [关闭]
【发布时间】:2011-06-20 09:36:48
【问题描述】:

当我单击一个复选框时,为什么没有添加选中的属性?。你可以在这里看到代码 http://jsfiddle.net/FCrSg/

【问题讨论】:

标签: javascript jquery html jquery-selectors jquery-events


【解决方案1】:

HTML 属性 checked 表示:在页面加载时选中默认。当复选框被点击时,这不会改变。

<input type="checkbox" checked="checked"> <!-- The HTML attribute -->

DOM 属性 checked 实际上是复选框的当前状态,并且是真/假。当复选框被点击时,这个改变,但在你检查 HTML 时不可见。

$('input:check')[0].checked == true;
// Whether or not the checkbox is currently checked

【讨论】:

【解决方案2】:

你想做什么?看看它是否被选中?

$('.user_roles').click(function(){ 
    console.log( $(this).is(':checked'));
});

http://jsfiddle.net/petersendidit/FCrSg/1/

【讨论】:

  • 上述解决方案对我来说工作得很好,但我也使用了 prop() 函数,它也工作得很好,但是对于相同的代码不起作用是什么原因请告诉我
  • 此回复并未真正回答问题。
【解决方案3】:

如果您想看到它出现在控制台中显示的元素上,请使用原生的setAttribute() 方法。

示例: http://jsfiddle.net/FCrSg/2/

this.setAttribute('checked',this.checked);

所以它看起来像这样:

$('.user_roles').click(function(){
    this.setAttribute('checked',this.checked);
    console.log( $(this) );
});

那么控制台应该给你:

<input class=​"user_roles" type=​"checkbox" checked=​"true">​

虽然您通常不需要这样的属性集。通常属性就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多