jQuery插入节点(移动节点)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"> <meta charset="UTF-8"> <title>b index</title> <link rel='stylesheet' type="text/css" href='b/css/bootstrap.css'> </head> <body style="margin:150px;"> <div id="div001"> <span id="spn001">1</span> <span id="spn002">2</span> <span id="spn003">3</span> </div> <div> <button id="btn001">click me</button> <button id="btn002">click me to create dom</button> <button id="btn003">click me to move dom</button> </div> <script type="text/javascript" src="js/jquery-1.11.1.js"></script> <script type="text/javascript" src="b/js/bootstrap.js"></script> <script type="text/javascript" src="js/index025.js"></script> </body> </html>
$(function() { $('#btn001').click(btn001Click); $('#btn002').click(btn002Click); $('#btn003').click(btn003Click); initSpnClick(); }); function btn001Click() { var $div001 = $('#div001'); $div001.append(createP('p n'));// L.append(in);其中L-list,in-item n createP('p n+1').appendTo($div001);// in.appendTo(L); $div001.prepend(createP('p 02'));// L.prepend(i1);其中i1-item 1 createP('p 01').prependTo($div001);// i1.prependTo(L); $div001.after(createP('p b02')); // a.after(b); createP('p b01').insertAfter($div001);// b.insertAfter(a); $div001.before(createP('p a01')); // b.before(a); createP('p a02').insertBefore($div001);// a.insertBefore(b); } function createP(txt) { return $('<p>' + txt + '</p>'); } function btn002Click() { var $p = $('<p><span>');// 这样得到的竟然是<p><span></span></p> // $p.html('this is in p and in span');// 这样又把span给替换了; $('span', $p).html('this is in span');// 用到了逗号操作符; $('#div001').append($p); } function btn003Click() { var $spn001 = $('#spn001'); var $div001 = $('#div001'); $div001.append($spn001);// 这样移动对象,其上面的事件还是保留的; } function initSpnClick() { $('span').click(function() { // 获取点击事件的对象: arguments[0].target.id console.log('%c' + arguments[0].target.id + ' click', 'font-size:16px;color:red'); }); }