JQuery .on()事件绑定,JQuery事件委托

浏览: 2,299次 日期:2017年12月09日 20:15:11 作者:青格勒

JQuery的.on()可以绑定一下几个常用的事件(click ,scroll ,focus ,blur ,input ,submit ,touchmove,mouseenter,mouseout…..),hover事件是不可以的,因为hover是mouseenter mouseout来制作出来的,详细的不在这里说了。

JQ的绑定事件书写格式:

<pre>
$('被委托方').on('事件','委托方',function(){
    执行的代码,这里this是触发原
});

被委托方:class、id、标签、document
委托方:class、id、标签
事件:click、scroll 、focus。多个需要使用英文,隔开 
</pre>

事件委托的比较通俗的解释:让别人代做事情就叫做委托。

如果页面刷新完成后,页面上新添加了一个标签,然后想给它一个点击事件,但是这个标签是后来的,所以普通事件没法在它身上运行。

这时候我们需要利用原本就在页面上的元素来委托这个事情然后去完成。

 

下面的代码是一个JQuery事件委托的例子,可以点击运行来看例子:

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<div id="box1" class="box">
    <pre>
    $('#box1').on('click','button',function(){
        $('#box1').append(button_v)
    });
        事件委托
    </pre>
    <button type="button">点击</button>
</div>
<div id="box2" class="box">
    <pre>
    $('#box2 button').click(function(){
        $('#box2').append(button_v);
    });
        普通事件
    </pre>
    <button type="button">点击</button>
</div>
<script type="text/javascript">
    $(document).ready(function(){
        var button_v = '<button type="button">点击</button>'
        $('#box1').on('click','button',function(){
            $('#box1').append(button_v);
        });
        $('#box2 button').click(function(){
            $('#box2').append(button_v);
        });
    });
</script>
<style type="text/css">
    body{ width:900px; margin:30px auto; font-family:"Microsoft YaHei";}
    #box1,#box2{ float:left; width:400px; margin:30px 25px; background:#999;}
    .box button{ display:block; width:80%; margin:10px auto;}
    .box em{ display:block; line-height:30px;}
    pre{ font-size:16px; color:#fff; background:#000; padding:15px;}
</style>

这里JQuery是使用百度的免费CDN,如果这个链接被取消的话需要复制到你的本地去运行了,别忘了引用1.7及以上版本的JQuery哦。

文章链接:http://cenggel.com/js/17.html

版权声明:文章《JQuery .on()事件绑定,JQuery事件委托》由青格勒编写,转载请带上文章链接。

本章内容纯属乱讲,如有雷同,纯属巧合。如有借鉴之处已表明出处。

点击任意位置关闭窗口,感谢您的支持。


打赏规则 - 为了避免对于打赏模式产生误解,说明一下几点内容:

  • 1.打赏纯粹自愿,金额不限,别太多,1块就行;
  • 2.打赏不能作为解答疑问的理由;
  • 3.打赏不能帮你做毕业设计或论文;
  • 4.打赏不能帮你做工作中的项目;
  • 5.打赏就是这不能那不能,只是单纯打赏而已。
  • 5.最后谢谢支持。
关闭
相关文章

发表评论

邮箱地址不会被公开。 必填项已用*标注