4

我只是想知道是否有人可以指出为什么应该使用 jQuery 事件绑定而不是原生 JavaScript。我的一位同事向我发送了以下代码。

document.forms[0].onsubmit = function () {
    if (Page_IsValid) {
        $("#dialog").dialog({
            height: 140,
            modal: true,
            resizable: false,
            title: ''

        });
        $(".ui-dialog-titlebar").hide();
    }
}

我告诉他把它改写为。

$(".form").submit(function () {
    if (Page_IsValid) {
        $(".dialog").dialog({ 
            height: 140,
            modal: true,
            resizable: false,
            title: '',
            open: function (event, ui) {
                $(".ui-dialog-titlebar").hide();
            }
        });
    }
});

但是当被问及为什么要使用我的代码时,除了语法清晰和约定之外,我无法提供任何具体原因。那么还有什么其他原因会使用第二个例子而不是第一个例子吗?如果不是,那么在这种情况下使用 jQuery 的真正优势是什么?

4

3 回答 3

3

One reason is you don't have to worry about trampling over previously-defined event callbacks. jQuery will queue them up and run all of them.

note: Your rewritten version will also attach the behavior to anything on the page with a class of form, while the original version attaches to the first form on the page, regardless of its class. This may not be what you want.

于 2012-05-08T00:50:02.840 回答
2

The problem with onsubmit event is that only one handler can be set per element and per event. In normal browser you can use addEventListener but what IE? Thanks to jQuery you can forget what browser running your script and just add many listeners to one element.

Or one to many, many to many or just one to one like in your first sample.

于 2012-05-08T00:52:10.347 回答
1

The second example will do better if there are multiple forms you want add submit functions to. Apart from that there is no technical reason to prefer the second over the former.

Consistency is a good enough reason for the second IMO. Seasoned developers will process either without thought, but green talent may find themselves having to mentally shift gears.

于 2012-05-08T00:52:54.877 回答