1 要求
将一段 HTML
脚本 封装成一个字符串,将这个字符串转换成一个jQuery
对象;然后将这个jQuery
对象添加到指定的元素中去
2 步骤
定义字符串
var str = '<div id="box01">hello world</div>'; //定义一个字符串
利用jQuery框架将字符串转换成jQuery对象
var box = $(str); // 利用jQuery将字符串转换成jQuery对象
打印输出转换得到的结果,判断是否转换成功
console.log(box); // 打印转换过来的jQuery对象
获取转换过来的jQuery
对象中的内容
console.log(box.html()); // 获取转化过来的jQuery对象中的内容
将装换过来的jQuery
对象添加到指定的元素中去
$("#parent").append(box); // 将转换过来的jQuery对象添加到指定元素中去
<!DOCTYPE html><!-- 给浏览器解析,我这个文档是html文档 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="Keywords" content="" />
<title></title>
<script type="text/javascript" src="../js/test.js"></script>
<script type="text/javascript" src="../js/jquery-1.4.3.js"></script>
<!-- <link rel="shortcut icon" href="../img/study04.ico"> -->
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
#parent {
width: 300px;
height: 300px;
background-color: skyblue;
}
</style>
<script type="text/javascript">
$(function() {
var str = '<div id="box01">hello world</div>'; //定义一个字符串
var box = $(str); // 利用jQuery将字符串转换成jQuery对象
console.log(box); // 打印转换过来的jQuery对象
console.log(box.html()); // 获取转化过来的jQuery对象中的内容
$("#parent").append(box); // 将转换过来的jQuery对象添加到指定元素中去
});
</script>
</head>
<body>
<div id="parent">
</div>
</body>
</html>
3 js代码执行顺序
直接写的js代码按照顺序执行
绑定的js
代码事件触发时执行
$(funcgion(){});
这里面的js代码是在body
加载完成后才执行
4 绑定数据到元素
4.1 要求:将某些数据绑定到指定元素
4.2 实现:利用jQuery
对象的data
方法
$("#box01").data("name", "warrior");
name 绑定数据的名称
warrior 被绑定的数据
console.log($("#box01").data("name"));
name 之前绑定好的数据的名称
<!DOCTYPE html><!-- 给浏览器解析,我这个文档是html文档 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="Keywords" content="" />
<title></title>
<script type="text/javascript" src="../js/test.js"></script>
<script type="text/javascript" src="../js/jquery-1.4.3.js"></script>
<!-- <link rel="shortcut icon" href="../img/study04.ico"> -->
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
#parent {
width: 300px;
height: 300px;
background-color: skyblue;
}
</style>
<script type="text/javascript">
$(function() {
// 将数据绑定到元素上
$("#box01").data("name", "warrior");
$("#box01").data("gender", "Male");
// 获取之前给元素绑定的数据
console.log($("#box01").data("name"));
console.log($("#box01").data("gender"));
});
</script>
</head>
<body>
<div id="box01">
</div>
</body>
</html>