美文网首页
事件委托节点操作

事件委托节点操作

作者: HDhandi | 来源:发表于2018-06-28 16:32 被阅读0次

(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(){
        /*
        给每个li绑定事件,一共绑定了8次,性能不高
        $('.list li').click(function() {
            alert($(this).html());
        });
        */
        /*
        事件委托:方法delegate,只绑定一次事件,冒泡触发
            参数:
                selector选择器:写入ul下面的所有要发生事件的元素,多个元素用空格隔开,例如‘li a span’
                eventType事件
                function要执行的操作
        
        $('.list').delegate('li', 'click', function() {
            //$(this)指发生事件的子集,即每个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)节点操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>节点操作</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>页面标题</h1>');
        /*插入子元素*/
        //div中插入span和p(末尾追加)
        // $('#div1').append($span);
        // $('#div1').append($p);
        // 把span和p插入div中
        $span.appendTo('#div1');
        $p.appendTo('#div1');
        //把子元素插入到父元素(前面追加)
        // prepend()
        // prependTo()
        //在div前边插入兄弟h1标题
        // $('#div1').before($h);
        $h.insertBefore('#div1');
        //在后边插入兄弟元素
        //after()
        //insertAfter()
        //删除p标签
        $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',//请求的服务器路径,实际开发中写文档接口的路径
        type: 'get',//分get/post请求
        dataType: 'json',//要读取什么格式的数据,xml script html upload
        // data:{page:1}//请求时要携带的参数
    })
    .done(function(data){//成功的时候会执行的函数
        alert(data.name);
        console.log(data);
    })
    .fail(function(){//失败的时候
        console.log("error");
    })
    /*.always(function(){//不论成功与否都会执行
        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可以跨域请求数据的原理:
        主要是利用了script标签可以跨域链接资源的特性
    */
    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',//跨域请求的地址,也可用相对路径js/data.js
        type: 'get',
        dataType: 'jsonp',//使用jsonp跨域请求
        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.360.cn/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.360.cn/suggest?',//请求360搜索的公开接口
                type: 'get',
                dataType: 'jsonp',//跨域请求
                data: {word: val}//携带参数
            })
            .done(function(data) {
                console.log(data);
                // alert(data.s.length);//10条数据
                $('.list').empty();//先清空列表
                //模拟搜索联想,循环插入新列表
                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");

相关文章

网友评论

      本文标题:事件委托节点操作

      本文链接:https://www.haomeiwen.com/subject/mdzgyftx.html