Binding onchange to dropdown

2020-03-01 08:32发布

I am little confused in binding onchange to select. I can see there are multiple ways of doing this.

html

<select id="ddl" onchange="test()"></select>

jquery

$(function(){

    $("#ddl").change(function(){
               return test();
           });

});

or

 $(function(){

    $("#ddl").bind("change", function(){
               return test();
           });

});

Among these 3 methods

  1. Which one is considered as a standard practice?
  2. Is there any merits with any of these methods?

3条回答
▲ chillily
2楼-- · 2020-03-01 08:46

all mentioned jquery methods seems to be equal, I would suggest using .change() making your code easier to read.

I've experienced that html onchange="" is rewritten by jquery bound events, but multiple calling to jquery .change() will chain the handlers which is usually wanted behavior.

To make the code clean, I'm using html onchange property only in simple programs which I know that will not have multiple event handlers and the code inside is really easy (usually one function).

查看更多
家丑人穷心不美
3楼-- · 2020-03-01 08:54

Instead of rebinding the <select> every time, you're better off just swapping its contents (the list of <option> elements) instead.

So use this as you already are:

$("#ItemsPerPage").change(function(e) { return updatePaging(); });

but when you update it, just swap out its contents ( where newSelectElement is the new <select> element):

function updateItemsPerPage( newSelectElement ) {
    $("#ItemsPerPage").empty().append( newSelectElement.childNodes );
}
查看更多
做自己的国王
4楼-- · 2020-03-01 08:57

You can also use .on

$('SELECT').on('change',function(){
   // code
});

Before jQuery 1.7, change() was simply an short cut for bind("change").

As of 1.7 however, on() has replaced bind("change"), so change() is a shortcut for that instead.

Therefore the best way would be either;

$("SELECT").bind("change", function(e) {});
$("SELECT").on("change", function(e) {});

I prefer the 2nd option as it also can applied automatically to the dynamically generated DOM.

查看更多
登录 后发表回答