javascript - Jquery 中的 bindType 与 delegateType

标签 javascript jquery

嘿伙计们,我刚刚浏览了 Jquery 文档,基本上遇到了以下代码:

jQuery.event.special.pushy = {
    bindType: "click",
    delegateType: "click"
};

该文档对 bindTypedelegateType 有以下解释,

When defined, these string properties specify that a special event should be handled like another event type until the event is delivered. The bindType is used if the event is attached directly, and the delegateType is used for delegated events. These types are generally DOM event types, and should not be a special event themselves.

现在我不明白以下内容:

如果直接附加事件,则使用bindType,并且 delegateType 用于委托(delegate)事件。

什么是直接附加委托(delegate)事件

谢谢。

亚历克斯-z

最佳答案

考虑 this brilliant article 中的示例:

HTML

<html>
<body>
<div id="container">
    <ul id="list">
        <li><a href="http://domain1.com">Item #1</a></li>
        <li><a href="/local/path/1">Item #2</a></li>
        <li><a href="/local/path/2">Item #3</a></li>
        <li><a href="http://domain4.com">Item #4</a></li>
    </ul>
</div>
</body>
</html>

JS(直接绑定(bind))

// Attach a directly bound event handler
$( "#list a" ).on( "click", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});

JS(委托(delegate)绑定(bind))

// Attach a delegated event handler
$( "#list" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.

关于javascript - Jquery 中的 bindType 与 delegateType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809367/

相关文章:

jquery - 在页面加载时调用jquery

javascript - 突出显示并向小时表添加文本

javascript - 在 Javascript 中将数组传递给 Web 方法

javascript - 针对 jQuery 中每个循环的嵌套 $(this)

jquery - Django Ajax 响应日期和时间格式

javascript - 将各种形状的 div 一起 float 成行

javascript - 删除 contenteditable div 中标签内字符串前后的空格

javascript - 创建 adonis js 新项目时出现错误

javascript - fs.readFile 返回 Buffer 对象和 toString 会使终端提示

javascript - React Native 按钮按下以控制导入的类状态