1、分析源码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript DOM对象和JQuery对象相互转换</title> <script type="text/javascript" src="jquery-1.11.2.js"></script> <script type="text/javascript"> /** * JavaScript DOM对象转换成JQuery对象 */ function javaScriptToJquery() { //DOM对象 var divObject = document.getElementById("div_body"); //jQuery对象 var $divObject = $(divObject); alert("JavaScript DOM对象转换成JQuery对象:"+divObject); } /** * JQuery对象转换成JavaScript DOM对象 */ function jqueryToJavaScript() { //jQuery对象 var $divObject = $("#div_body"); //DOM对象 var divObject = $divObject[0]; //DOM对象 var divObject1 = $divObject.get(0); alert("JQuery对象转换成JavaScript DOM对象方法一:"+divObject+"\n"+"JQuery对象转换成JavaScript DOM对象方法二:"+divObject1); } </script> </head> <body> <div id="div_body">HTML</div> <input type="button" id="btn1" value="JavaScript DOM对象转换成JQuery对象" onclick="javaScriptToJquery()"/> <input type="button" id="btn2" value="JQuery对象转换成JavaScript DOM对象" onclick="jqueryToJavaScript()"/> </body> </html>
2、运行结果
(1)初始化
(2)点击”JavaScript DOM对象转换成JQuery对象“按钮
(3)点击”JQuery对象转换成JavaScript DOM对象“按钮
3、分析说明
(1)JavaScript DOM对象转换成JQuery对象
//DOM对象
var divObject = document.getElementById("div_body");
//jQuery对象
var $divObject = $(divObject);
(2)JQuery对象转换成JavaScript DOM对象
方法一:
//jQuery对象
var $divObject = $("#div_body");
//DOM对象
var divObject = $divObject[0];
方法二:
//jQuery对象
var $divObject = $("#div_body");
//DOM对象
var divObject1 = $divObject.get(0);
时间: 2024-10-12 08:16:26