JS .checked vs jquery attr('checked'),有什么区别? [英] JS .checked vs jquery attr('checked'), what is the difference?

查看:146
本文介绍了JS .checked vs jquery attr('checked'),有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法想出这个。根据 W3学校已检查的属性设置或返回已检查的状态复选框。

I can't figure this one out. According to W3 Schools, the checked property sets or returns the checked state of a checkbox.

那么为什么 $('input')。选中? $('div')。slideDown():$('div')。slideUp(); 不起作用?

使用prop但是确实有效。

Using prop however, does work.

$('input')。prop('checked')? $('div')。slideDown():$('div')。slideUp();

这是一个复选框,根据数据库值进行检查。

This is for a checkbox that is checked based on a database value.

推荐答案

已检查是一个DOM元素属性所以在DOM元素而不是jQuery对象上使用它。

checked is a DOM element property so use it on DOM elements instead of jQuery objects.

$('input')[0].checked

如果你有一个jQuery对象,请改用 prop attr ,因为您正在检查房产。仅供参考:

if you have a jQuery object, use prop instead of attr since you are checking a property. Just as a reference:

$("<input type='checkbox' checked='checked'>").attr("checked") // "checked"
$("<input type='checkbox' checked='foo'>").attr("checked") // "checked"
$("<input type='checkbox' checked>").attr("checked") // "checked"
$("<input type='checkbox'>").attr("checked") // undefined

[0] .getAttribute(选中)将返回实际值。

prop 将返回 true false ,具体取决于该属性是否存在

prop will return true or false based on whether or not the attribute exists at all

这篇关于JS .checked vs jquery attr('checked'),有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆