jquery——关于jquery对象与dom对象的转换问题
一、转换方法小结
1.dom转jquery对象
(1) $(dom对象)
2.jquery对象转dom
(1) $(dom对象)[索引值]
(2) $(dom对象).get(索引值)
二、遇到的问题
最近学习jquery学习过程中,碰到了jquery对象与dom对象的转换问题,最主要的是转换的时机。当前的对象转换的结论是:
当需要使用在代码块内使用对方的方法时使用。
<!--以下为想要实现的页面-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>反选/全选/全不选</title>
</head>
<body>
反选<input type="checkbox" id="antiSelect" name="">
全选<input type="checkbox" id="selectAll" name="">
全不选<input type="checkbox" id="antiSelectAll" name="">
<br>
<div id="inputDiv">
吃饭<input type="checkbox" id="choice1" name="">
跑步<input type="checkbox" id="choice2" name="">
玩游戏<input type="checkbox" id="choice3" name="">
</div>
</body>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/fanxuan.js"></script>
</html>
// $(function(){
// alert("hello jquery");
// })
//
$(function(){
// 实现反选/全选/全不选
// 当点击全选,所有复选框为选中状态(checked)
// 点击全不选,所有复选框选中属性为空
// 点击反选,所有复选框选中属性反转
// 三个选项任意一个选中后,其他两个均为未选中状态。
var selectAll = $("#selectAll");
var antiSelect = $("#antiSelect");
var antiSelectAll = $("#antiSelectAll");
// 获取所有的喜好选择项
var choice1 = $("#choice1");
var choices = $("input[id*=choice]");
// alert(choices.length)
selectAll.click(function(){
if (selectAll.prop("checked")) {
// 设置另外两项为false
// alert(selectAll)
selectAll.siblings().prop("checked",false);
// 设置所有的喜好项为选中
choice1.prop("checked","checked");
choice1.siblings().prop("checked","checked");
}
})
antiSelectAll.click(function(){
if (antiSelectAll.prop("checked")) {
// 设置另外两项为false
// alert(selectAll)
antiSelectAll.siblings().prop("checked",false);
// 设置所有的喜好项为选中
choice1.prop("checked",false);
choice1.siblings().prop("checked",false);
}
})
alert($(choices)[1].checked)
antiSelect.click(function(){
if (antiSelect.prop("checked")) {
// 设置另外两项为false
// alert(selectAll)
antiSelect.siblings().prop("checked",false);
// 设置所有的喜好项为选中
for(var i = 0; i < choices.length; i++){
// alert($(choices)[i].checked)
if ($(choices)[i].checked == true) {
$(choices)[i].checked == false;
}else{
$(choices)[i].checked == true;
}
}
}
})
})
问题在于在js代码中,想要实现反选的相应功能时(antiSelect),无法使用choices这一jquery对象数组来循环使用jquery的prop方法,一使用页面就会报 is not a function 的错误,因此在此处的想法是将该对象组转化为dom的对象数组。
注:此处代码是未实现的,需要修改。