jQuery 判断元素整理汇总

2020-05-23 06:16:21易采站长站整理

alert 时:前五个为 checked,最后一个为 undefined。

所以 jQuery 在这里要注意一下,它取的值与显示情况不符。

应付 radio 更好的办法

有时候,我们只需要关心已经选中的 radio,所以可以这么做:


<input type="radio" name="r1" value="1" checked="true" />
<input type="radio" name="r1" value="2" checked="false" />
<input type="radio" name="r1" value="3" checked="disabled" />
<input type="radio" name="r1" value="4" checked="hahaha" />
<input type="radio" name="r1" value="5" checked />
<input type="radio" name="r1" value="6" />
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
<!--
alert($("input:radio:checked").val());
//-->
</script>

这样结果就是 5。

是否禁用


<input type="text" disabled="true" />
<input type="text" disabled="false" />
<input type="text" disabled="disabled" />
<input type="text" disabled="hahaha" />
<input type="text" disabled />
<input type="text" />
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
<!--
$("input").each(function (){
alert($(this).attr("disabled"));
});
//-->
</script>

如上代码,有六个 input,显示为:前五个为禁用状态,最后一个为可用。

alert 时:前五个为 disabled,最后一个为 undefined。

也就是说只要标签中有 disabled,即为禁用,与其属性值无关,而 jQuery 取属性值时也是这么认的。要判断是否禁用,用 attr(“disabled”) == “disabled” 即可。