jQuery中的.change()与.on("change",handler) [英] .change() vs .on( "change", handler ) in jQuery

查看:845
本文介绍了jQuery中的.change()与.on("change",handler)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用jQuery处理下拉菜单中的更改触发器时,我遇到了一个问题.

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

我使用2段代码:

//---------- 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.

你有什么主意吗?

我的jQuery版本:1.11.1,并且已经在Chrome 38,Firefox 32和IE 11上进行了测试.

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

- @JanR&爽朗:看起来像这样:

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

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

我使用过Rails 4.1,而 arr 是一个包含数字的数组.

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

- 我发现问题出在Rails的Asset Pipeline,而不是jQuery.

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

我将JS代码放在script标记中,并且在两种情况下都可以使用,但是当我将其放在assets文件夹中时,就会发生此问题.

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.

感谢您的快速回复!

推荐答案

我建议使用案例1,因为它是组成文档以加载更改事件,如果您选择的元素是动态生成的,请使用情况1将有效.

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.

另外jquery doc表示,.change()是.on("change",handler)的快捷方式,所以我认为最终将使用.on回调.

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

这篇关于jQuery中的.change()与.on("change",handler)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆