简体   繁体   English

如何将此javascript / jQuery转换为“非内联”功能?

[英]How can I convert this javascript / jQuery into a “not inline” function?

I hvae the following code: 我拥有以下代码:

$(".openDialog").live("click", function (e) {
    e.preventDefault();

    $("<div></div>")
    .addClass("dialog")
    .attr("id", $(this).attr("data-dialog-id"))
    .appendTo("body")
    .dialog({
        title: $(this).attr("data-dialog-title"),
        close: function () { $(this).remove() },
        modal: true
    })
    .load(this.href);
});
$(".close").live("click", function (e) {
    e.preventDefault();
    $(this).closest(".dialog").dialog("close");
});

Can someone explain how I can decouple the functions form the actions? 有人可以解释我如何将功能与动作分离吗? I am a bit confused with how to do this. 我对如何做到这一点感到困惑。

Also what is the purpose of "live" ? 另外,“直播”的目的是什么? I heard before someone suggesting "on". 我听到有人建议“开”。 Is "on" better than "live" and how does it actually work? “在线”比“实时”好吗?它实际上是如何工作的?

Just break the functions out, then pass the function name: 只需将函数分解,然后传递函数名称:

close: closeFunction    

function closeFunction() { 
   $(this).remove() 
}

$(".close").live("click", closeClick);

function closeClick(e) {
    e.preventDefault();
    $(this).closest(".dialog").dialog("close");
}

on is indeed better than live . on确实优于live Both allow you to wire up events to dynamically added content, but the former is more efficient, and the latter is deprecated, . 两者都允许您将事件连接到动态添加的内容,但是前者效率更高,而后者则已弃用。 Here's how you'd use it 这是您的使用方式

$(document).on("click", ".close", closeClick);

or, ideally, if all these .close buttons were to be in a container, say, a div with id foo, you could more efficiently do 或者,理想情况下,如果所有这些.close按钮都位于容器中,例如id foo的div,则可以更有效地执行

$("#foo").on("click", ".close", closeClick);

or for jQuery pre 1.7 you'd have to settle for delegate 或对于jQuery 1.7之前的版本,您必须满足delegate

$("#foo").delegate(".close", "click", closeClick);

Also what is the purpose of "live" ? 另外,“直播”的目的是什么? I heard before someone suggesting "on". 我听到有人建议“开”。 Is "on" better than "live" and how does it actually work? “在线”比“实时”好吗?它实际上是如何工作的?

Since jQuery 1.7 .live is deprecated: http://api.jquery.com/live/ 由于不推荐使用jQuery 1.7 .live,因此: http : //api.jquery.com/live/

As of jQuery 1.7 , the .live() method is deprecated. jQuery 1.7开始 ,不推荐使用.live()方法。 Use .on() to attach event handlers. 使用.on()附加事件处理程序。 Users of older versions of jQuery should use .delegate() in preference to .live(). 旧版jQuery的用户应该使用.delegate()而不是.live()。

More about new .on() feature: http://blog.jquery.com/2011/11/03/jquery-1-7-released/ 有关新的.on()功能的更多信息: http : .on()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM