Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - .change() vs .on( "change", handler ) in jQuery

I have an issue when I use jQuery to handle the trigger of change on my drop-down.

I use 2 pieces of code:

//---------- Case 1
$(document).on("change", "#drop-down-id", function () {
    alert(this.value);
});
//----------Case 2
$("#drop-down-id").change(function () {
    alert(this.value);
});

The first one running smoothly, but the second one is not triggered when I start the browser, but after I refresh my site, it works.

Do you have any idea?

My jQuery version: 1.11.1, and I've tested on Chrome 38, Firefox 32 and IE 11.

-- Edit: @JanR & Cheery: It seems like this:

<select id="drop-down-id">
    <% arr.each do |option| %>
        <option value="<%= option %>"><%= option %></option>
    <% end %>
</select>

I've used Rails 4.1 and arr is an array contains numbers.

-- Edit: I found out that the issue came from the Asset Pipeline of Rails, not the jQuery.

I put the JS code inside a script tag and it works in both case, but when I put it in the assets folder, the issue happens.

Thank you for your quick replies!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recommend using case 1, since it is composed document to load change event, if you choose the elements are dynamically generated, use case 1 will be effective.

Also jquery doc said, .change () is a shortcut for .on ("change", handler), so I think eventually will use .on callback.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...