jQuery事件、$().css、$('p').each

发布时间:2019-05-28 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了jQuery事件、$().css、$('p').each脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Cheat Sheet

https://oscarotero.com/jquery/


$().css

$().css 实际上是修改 inline style


$('p').each

$('p').each 方法可通过 return false 终止

$('*').each 实际上每轮并不是用 jQuery Dom Element 去调用方法

运行

function numberAddr() {
    console.LOG(this);
    console.log($(this));
}

$('p').each(numberAddr);

会得到

jQuery事件、$().css、$(\'p\').each


Event Listening

monITorevents

Chrome Dev Tool 提供了一个monitorEvents方法

VAR imgage = $('img')
monitorEvents(image)

$(target).on(targetEvent,function)

示例

/*
Use jquery to set up an event listener. Your event listener must:
    1. listen to the #my-button element
    2. listen for a `click` event
    3. PErform the following actions when the button is clicked:
        a. remove the #my-button element From the DOM
        b. add the `success` class to the body
*/

$('#mu-button').on('click',function() {
    $(this).detach();
    $('body').addClass('success');
});

可写为 ('#mu-button').click(function(){})

更多:
jQuery Event Api


事件代理

上面说到的 on 方法可以有三个参数
比如 $( '.container' ).on( 'click', 'article', function() { … });
给 .container 添加click事件的监听器,被点击时检查 target element 是否是 article

下面这段代码,当为 article 添加监听器时,article 并未被创建,所以添加失败。这时就应用事件代理的方法。

$( 'article' ).on( 'click', function() {
    $( 'body' ).addClass( 'selected' );   
});

$( 'body' ).append( '<article> <h1>Appended Article</h1> <p>Content for the new article </p> </article>' );

或者一个 ul 中有很多的 li 时,使用事件代理的方法就不需要为每一个 li 都专门设置一个监听器

<ul id="rooms">
    <li>Room 1</li>
    <li>Room 2</li>
            .
            .
            .
    <li>Room 999</li>
    <li>Room 1000</li>
</ul>

Event Object

$( '#myAnchor' ).on( 'click', function( evt ) {
    evt.preventDefault();
    console.log( 'You clicked a link!' );
});

可通过 preventDefault 方法来告诉浏览器不执行默认的行为。比如在这里点击锚点将不会跳转到指定位置。(大概是先执行自定义的行为后执行默认行为)

event.keyCode 能得知按下的哪个键 - 如果监听一个特定的键则没有价值
event.pageXevent.pageY 能得知被点击的坐标
event.type 能得知事件类型 - 当监听多个事件的时候很有用

更多:
jQuery's Event Object
event.target property

脚本宝典总结

以上是脚本宝典为你收集整理的jQuery事件、$().css、$('p').each全部内容,希望文章能够帮你解决jQuery事件、$().css、$('p').each所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。