实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <style> .obj-b, .obj-aa { height: 100px; width: 300px; background-color: brown; color: white; line-height: 100px; text-align: center; } </style> <body> <h3>JS对象的创建、属性和方法</h3> <button id="but-a">弹出对象one的属性</button> <button id="but-b">弹出对象two的属性</button> <button id="but-c">弹出对象three的属性</button> <p id="obj-a" class="obj-aa"></p> <p id="obj-cc" class="obj-b"></p> <ul id="each-a"> $.each()遍历输出<button id="but-d">点击开始</button> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </body> </html> <script> //创建一个对象---定义、创建实例 var object_new = new Object(); //添加属性和方法 object_new.name = "xiaohu"; object_new.age = 20; object_new.sex = "男"; object_new.work = function() { $('p.obj-b').text('这是object_new对象的一个方法'); } //调用对象的方法--1 object_new.work(); //调用对象的属性--1 $('#obj-a').text(object_new.name); //调用对象的属性--2 $('#but-a').click(function() { $('#obj-a').text('这是object_new对象的age属性---' + object_new['age']); }); //创建一个对象 var object_three = { name: "xiaomao", age: 22, sex: "女", address: [ '河南省', '郑州市', '新郑市', '新华路小学', "三年级一班" ], work: function() { $('p.obj-b').text('这是object_three对象的一个方法'); } }; //调用对象的属性--3-1 $('#but-c').click(function() { $('#obj-cc').text('这是object_three对象的age属性---' + object_three['age']); }); //调用对象的方法--3-2 $('#but-c').dblclick(function() { object_three.work(); }); $('#obj-cc').mouseenter(function() { $('#obj-cc').text('这是object_three对象的age属性---' + object_three['address'][0]); }); //遍历 var each_num = 0; $('#but-d').click(function() { $('#each-a li').each(function() { $(this).text(object_three['address'][each_num]); each_num++; }); }); </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:JS对象真多,直接学JQ吧!