zoukankan      html  css  js  c++  java
  • jQuery 事件代理时的this

    在jQuery使用on方法进行事件代理的时候,this是有多种变化的.下面开始对其进行研究

    HTML的代码:

    <ul id="selected-plays" class="clear-after">
            <li>Comedies
              <ul>
                <li><a href="/asyoulikeit/">As You Like It</a></li>
                <li>All's Well That Ends Well</li>
                <li>A Midsummer Night's Dream</li>
                <li>Twelfth Night</li>
              </ul>
            </li>
            <li>Tragedies
              <ul>
                <li><a href="hamlet.pdf">Hamlet</a></li>
                <li>Macbeth</li>
                <li>Romeo and Juliet</li>
              </ul>
            </li>
            <li>Histories
              <ul>
                <li>Henry IV (<a href="mailto:henryiv@king.co.uk">email</a>)
                  <ul>
                    <li>Part I</li>
                    <li>Part II</li>
                  </ul>
                </li>
                <li><a href="http://www.shakespeare.co.uk/henryv.htm">Henry V</a></li>
                <li>Richard II</li>
              </ul>
            </li>
          </ul>

    显示效果为:

    然后我们使用不同方式对点击<li>元素的响应.

    1 如果on函数中没有没有第二个参数,且绑定的元素唯一,则this指向on前绑定的元素

    $('#selected-plays').on('click',function(e){
        console.log(this);
    })

    2 如果绑定的元素不唯一

    $('#selected-plays li').on('click',function(e){
        console.log(this);
    })

    因为li有多个匹配元素,所以当元素点击的时候会向上冒泡,直达最外层,比如此时点击

    点击事件会触发以下元素响应(这是jQuery的遍历机制).

    使用禁止冒泡:

    $('#selected-plays li').on('click',function(e){
        console.log(this);
        e.stopPropagation();})

    此时this就只有最底层的li响应了.

    3 那么on中有第二个参数:

    $('#selected-plays').on('click','li',function(e){
        console.log(this);})

    此处结果跟在on前绑定的结果一样,只不过返回的值不一样(返回值为on前绑定的jQuery对象)

    $('#selected-plays li').on('click',function(e){})

    同样的,如果第二个参数唯一的话,也等同于on前绑定唯一的jQuery对象

    4 还有一个很重要的情况,即绑定在document上,这也是事件代理中最常用的形式.

    $(document).on('click','li',function(e){
        console.log(this);
    })

    同样的,会冒泡直到顶层document,同样可以使用stopPropagation()

    $(document).on('click','li',function(e){
        console.log(this);
        e.stopPropagation();})

    总结:click会由当前点击元素最近的匹配元素一直冒泡到document中

  • 相关阅读:
    web单机优化
    html标签
    html基础
    jenkins api
    cobbler api
    Cobbler安装配置简单使用
    ubuntu 12.04下搭建web服务器(MySQL+PHP+Apache) 教程
    在ubuntu12.04上安装6款顶级漂亮的BURG主题
    Setting up an OpenGL development environment in ubuntu
    c++ list 容器
  • 原文地址:https://www.cnblogs.com/BigJ/p/8559307.html
Copyright © 2011-2022 走看看