【问题标题】:jQuery-checked radio button doesn't get checked despite having "checked" attribute set to "checked"尽管将“checked”属性设置为“checked”,但 jQuery-checked 单选按钮不会被选中
【发布时间】:2016-01-21 23:25:50
【问题描述】:

我使用.attr('checked', true); 手动检查了一个单选按钮(因为prop( 'checked', true); 在我的情况下似乎没有做任何事情)。

虽然单选按钮在标记中确实获得了等于checkedchecked 属性,但单选按钮仍未选中(在页面上,所有单选按钮仍处于未选中状态) .

这怎么可能?

jQuery:

$( '.variations_fieldset input[value="Every 2 months"]' ).attr('checked', true);

获得的HTML:

<fieldset class="variations_fieldset">
    <input type="radio" data-attribute_name="attribute_billing" name="attribute_billing" id="billing1" value="Once Off">
    <label for="billing1">Once Off</label>
    <input type="radio" data-attribute_name="attribute_billing" name="attribute_billing" id="billing2" value="Every 1 month">
    <label for="billing2">Every 1 month</label>
    <input type="radio" data-attribute_name="attribute_billing" name="attribute_billing" id="billing3" value="Every 2 months" checked="checked">
    <label for="billing3">Every 2 months</label>
</fieldset>

【问题讨论】:

  • 请发一个完整的代码示例。
  • 你是否在使用任何单选按钮插件,例如 css 样式?
  • 是的,但是 CSS 是否可以防止单选按钮看起来被选中,即使它确实被选中了?
  • 在您的示例中,您在最后一个输入中已经有 checked="checked",但即使没有它,jQuery 也可以工作:jsfiddle.net/j08691/e0tpgekm
  • 属性更新实际上并没有添加您可以看到的属性-它会更改内部状态,因此.prop("checked", true) 是正确的方法-您可以使用$(":checked") 查找结果

标签: jquery radio-button


【解决方案1】:

始终使用prop 来访问元素的底层属性,而不是attr

$( '.variations_fieldset input[value="Every 2 months"]' ).prop('checked', true);

attr 只是更改 DOM,但并不总是设置底层属性。

请注意:prop 不会更新 attr,因此您无法在 DOM 检查器中看到更改。

JSFiddle: https://jsfiddle.net/e0tpgekm/1/

【讨论】:

  • 属性更改不会向单选按钮添加“选中”属性。
  • @shawnt00: OP 可能没有意识到如果你使用 prop,attr 的变化在 DOM 中是不可见的。你不能总是从表面上看待这样的陈述。
  • @TrueBlueAussie 我不反对。 OP说它没有在页面上检查。这是它应该做的吗?
  • prop 唯一保证在所有浏览器上检查它的东西。你还有其他事情要发生。
  • @drake035 问:PHP 不应该看到“已检查”...它不应该看到带有选定值的名称-值对吗?
【解决方案2】:

如果你使用的是 1.6 之前的 jQuery,试试这个:

.attr('checked','checked');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2011-03-08
    • 2013-07-24
    • 2013-10-01
    • 1970-01-01
    • 2017-11-17
    • 2011-06-20
    相关资源
    最近更新 更多