In versions of jQuery before 1.6 use:
$('input[name="correctAnswer"]').attr('checked', false);
In versions of jQuery after 1.6 you should use:
$('input[name="correctAnswer"]').prop('checked', false);
but if you are using 1.6.1+ you can use the first form (see note 2 below).
Note 1: it is important that the second argument be false and not "false" since "false" is not a falsy value. i.e.
if ("false") {
alert("Truthy value. You will see an alert");
}
Note 2: As of jQuery 1.6.0, there are now two similar methods, .attr
and .prop
that do two related but slightly different things. If in this particular case, the advice provide above works if you use 1.6.1+. The above will not work with 1.6.0, if you are using 1.6.0, you should upgrade. If you want the details, keep reading.
Details: When working with straight HTML DOM elements, there are properties attached to the DOM element (checked
, type
, value
, etc) which provide an interface to the running state of the HTML page. There is also the .getAttribute
/.setAttribute
interface which provides access to the HTML Attribute values as provided in the HTML. Before 1.6 jQuery blurred the distinction by providing one method, .attr
, to access both types of values. jQuery 1.6+ provides two methods, .attr
and .prop
to get distinguish between these situations.
.prop
allows you to set a property on a DOM element, while .attr
allows you to set an HTML attribute value. If you are working with plain DOM and set the checked property, elem.checked
, to true
or false
you change the running value (what the user sees) and the value returned tracks the on page state. elem.getAttribute('checked')
however only returns the initial state (and returns 'checked'
or undefined
depending on the initial state from the HTML). In 1.6.1+ using .attr('checked', false)
does both elem.removeAttribute('checked')
and elem.checked = false
since the change caused a lot of backwards compatibility issues and it can't really tell if you wanted to set the HTML attribute or the DOM property. See more information in the documentation for .prop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…