事件委托

(1)事件委托

  <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件委托</title>
<style type="text/css">
    .list{
        list-style: none;
    }
    .list li{
        height: 30px;
        background-color: green;
        margin-bottom: 10px;
        color: #fff;
    }
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        /*
        給每個(gè)li綁定事件,一共綁定了8次,性能不高
        $('.list li').click(function() {
            alert($(this).html());
        });
        */
        /*
        事件委托:方法delegate,只綁定一次事件,冒泡觸發(fā)
            參數(shù):
                selector選擇器:寫入ul下面的所有要發(fā)生事件的元素,多個(gè)元素用空格隔開,例如‘li a span’
                eventType事件
                function要執(zhí)行的操作
        
        $('.list').delegate('li', 'click', function() {
            //$(this)指發(fā)生事件的子集,即每個(gè)li
            alert($(this).html());
            //取消委托
            $('.list').undelegate();
        });
    })
</script>
</head>
<body>
<ul class="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
</ul>
</body>
</html>

(2)節(jié)點(diǎn)操作

  <!DOCTYPE html>
  <html lang="en">
  <head>
<meta charset="UTF-8">
<title>節(jié)點(diǎn)操作</title>
<style type="text/css">
    
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        var $span = $('<span>span元素</span>');
        var $p = $('<p>p段落元素</p>');
        var $h = $('<h1>頁面標(biāo)題</h1>');
        /*插入子元素*/
        //div中插入span和p(末尾追加)
        // $('#div1').append($span);
        // $('#div1').append($p);
        // 把span和p插入div中
        $span.appendTo('#div1');
        $p.appendTo('#div1');
        //把子元素插入到父元素(前面追加)
        // prepend()
        // prependTo()
        //在div前邊插入兄弟h1標(biāo)題
        // $('#div1').before($h);
        $h.insertBefore('#div1');
        //在后邊插入兄弟元素
        //after()
        //insertAfter()
        //刪除p標(biāo)簽
        $p.remove();    
    })
    </script>
  </head>
<body>
<div id="div1"></div>
</body>
</html>

(3)ajax

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
<style type="text/css">
    
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $.ajax({
        url: 'data.json',//請(qǐng)求的服務(wù)器路徑,實(shí)際開發(fā)中寫文檔接口的路徑
        type: 'get',//分get/post請(qǐng)求
        dataType: 'json',//要讀取什么格式的數(shù)據(jù),xml script html upload
        // data:{page:1}//請(qǐng)求時(shí)要攜帶的參數(shù)
    })
    .done(function(data){//成功的時(shí)候會(huì)執(zhí)行的函數(shù)
        alert(data.name);
        console.log(data);
    })
    .fail(function(){//失敗的時(shí)候
        console.log("error");
    })
    /*.always(function(){//不論成功與否都會(huì)執(zhí)行
        console.log("always");
    })*/;
</script>
</head>
<body>

</body>
</html>

(4)jsonp

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp</title>
<style type="text/css">
    
</style>
<!-- <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> -->
<script type="text/javascript">
    // alert($);//function(a,b){return new n.fn.init(a,b)}
    /*
    jsonp可以跨域請(qǐng)求數(shù)據(jù)的原理:
        主要是利用了script標(biāo)簽可以跨域鏈接資源的特性
    */
    function aa(dat){
        alert(dat.name);
    }
</script>
<script type="text/javascript" src="js/data.js"></script>
</head>
<body>

</body>
</html>

(5)jQuery-jsonp

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery-jsonp</title>
<style type="text/css">
    
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $.ajax({
        url: 'http://localhost:8080/1803/js/data.js',//跨域請(qǐng)求的地址,也可用相對(duì)路徑j(luò)s/data.js
        type: 'get',
        dataType: 'jsonp',//使用jsonp跨域請(qǐng)求
        jsonpCallback:'aa'
    })
    .done(function(data) {
        alert(data.name);
    })
    .fail(function() {
        console.log("error");
    });
</script>
</head>
<body>

</body>
</html>

(6)jsonp公開接口

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp公開接口</title>
<style type="text/css">
    
</style>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    //360搜索的公開接口
    //https://sug.so.#/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=s
    $(function(){
        $('#txt01').keyup(function(){
            var val = $(this).val();
            $.ajax({
                url: 'https://sug.so.#/suggest?',//請(qǐng)求360搜索的公開接口
                type: 'get',
                dataType: 'jsonp',//跨域請(qǐng)求
                data: {word: val}//攜帶參數(shù)
            })
            .done(function(data) {
                console.log(data);
                // alert(data.s.length);//10條數(shù)據(jù)
                $('.list').empty();//先清空列表
                //模擬搜索聯(lián)想,循環(huán)插入新列表
                for(var i=0; i<data.s.length; i++){
                    var $li = $('<li>'+data.s[i]+'</li>');
                    $li.prependTo('.list');
                }
            })
            .fail(function() {
                console.log("error");
            });
        })
    })
    
</script>
</head>
<body>
<input type="text" id="txt01">
<ul class="list"></ul>
</body>
</html>

(7)

  /*
  NodeJS Static Http Server - http://github.com/thedigitalself/node-static-http-server/
  By James Wanga - The Digital Self
  Licensed under a Creative Commons Attribution 3.0 Unported License.
  A simple, nodeJS, http development server that trivializes serving static files.
  This server is HEAVILY based on work done by Ryan                   Florence(https://github.com/rpflorence) (https://gist.github.com/701407). I merged     this code with suggestions on handling varied MIME types found at Stackoverflow (http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs).
To run the server simply place the server.js file in the root of your web     application and issue the command 
$ node server.js 
or 
    $ node server.js 1234 
    with "1234" being a custom port number"
  Your web application will be served at http://localhost:8888 by default or     http://localhost:1234 with "1234" being the custom port you passed.
  Mime Types:
  You can add to the mimeTypes has to serve more file types.
  Virtual Directories:
  Add to the virtualDirectories hash if you have resources that are not children of the root directory
*/
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;

var mimeTypes = {
"htm": "text/html",
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"js": "text/javascript",
"css": "text/css",  
"json":"text/json",  
"eot":"application/vnd.ms-fontobject",  
"svg":"image/svg+xml",  
"ttf":"application/octet-stream",  
"woff":"application/font-woff",  
"woff2":"application/font-woff"
  };

  var virtualDirectories = {
//"images": "../images/"
  };

  http.createServer(function(request, response) {

    var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri)
    , root = uri.split("/")[1]
    , virtualDirectory;

      virtualDirectory = virtualDirectories[root];
      if(virtualDirectory){
    uri = uri.slice(root.length + 1, uri.length);
    filename = path.join(virtualDirectory ,uri);
  }

    fs.exists(filename, function(exists) {
    if(!exists) {
  response.writeHead(404, {"Content-Type": "text/plain"});
  response.write("404 Not Found\n");
  response.end();
  console.error('404: ' + filename);
  return;
}

if (fs.statSync(filename).isDirectory()) filename += '/index.html';

fs.readFile(filename, "binary", function(err, file) {
  if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    console.error('500: ' + filename);
    return;
  }

  var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
  response.writeHead(200, {"Content-Type": mimeType});
  response.write(file, "binary");
  response.end();
  console.log('200: ' + filename + ' as ' + mimeType);
});
  });
  }).listen(parseInt(port, 10));

  console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown")
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容