简体   繁体   English

jQuery:选中不与初始(HTML属性)单选输入一起使用

[英]jQuery :checked not working with initial (HTML attribute) radio input

Please inspect the following Console output, note that the 1st input has checked attribute and is selected: 请检查以下控制台输出,请注意,第一个输入已选中属性,并且已选中:

在此处输入图片说明

You can see I have 2 radio input s, 1 is checked , however neither selector nor prop nor is works for it. 你可以看到我有2个单选input S,被checked ,但没有选择,也没有prop ,也不is因为它的作品。 The code works correctly if I manually click on one of the radio. 如果我手动单击其中一个收音机,代码将正常工作。 Here is my HTML: 这是我的HTML:

<div class="col-sm-6">
    Type:
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default active">
            <input type="radio" name="generator-type" id="opt-type-passphrase" value="0" autocomplete="off" checked>
            Passphrase
        </label>
        <label class="btn btn-default">
            <input type="radio" name="generator-type" id="opt-type-password" value="1" autocomplete="off">
            Password
        </label>
    </div>
</div>

Why is the code not working when the page loads when I haven't clicked any radio? 为什么在我未单击任何收音机的情况下加载页面时代码不起作用? Is there a way to fix it? 有办法解决吗?

EDIT : Found the problem, I have this code in the page load: 编辑 :发现问题,我在页面加载中有以下代码:

        $("input[name='generator-type'][value=" + this.Options.Type + "]").prop("checked", "");

The correct solution is using: 正确的解决方案是使用:

.prop("checked", true)

But can anyone please explain how it work? 但是谁能解释一下它是如何工作的? Why is there the checked attribute, but prop function is still false? 为什么有checked属性,但是prop函数仍然为false?

Try .is(':checked') instead of .is('checked') . 尝试使用.is(':checked')而不是.is('checked') Please check this Fiddle . 请检查此小提琴

You're missing a colon in the is-checked code: 您在is-checked代码中缺少冒号:

temp.is(":checked")

instead of 代替

temp.is("checked")

You need to check like this 你需要这样检查

$( ... ).is(':checked')

Why? 为什么? Because the jquery is method accepts a css selector which it uses to filter the currently matched elements. 因为jquery is method,所以它接受一个css选择器,该选择器用于过滤当前匹配的元素。

Thus temp.is('checked') will only be true if the temp elements have the checked tag. 因此,仅当temp元素具有checked标签时, temp.is('checked')才为true。 In your case they have the input tag so do not match. 在您的情况下,它们具有input标签,因此不匹配。

Using :checked matches on the css pseudo selector for whether the current element is checked or not. 在CSS伪选择器上使用:checked匹配项可确定是否检查了当前元素。 This is what you want. 这就是你想要的。

Knowing this, you could also use $( ... ).is('[checked]') , which will return true if the matched elements have the checked attribute. 知道这一点,您还可以使用$( ... ).is('[checked]') ,如果匹配的元素具有checked属性,它将返回true。 That's probably what you were trying to do originally. 那可能就是您最初想要做的。 Though, the conventional way is to use :checked . 虽然,常规方法是使用:checked

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

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