Click and Change事件不适用于jquery-select2选项 [英] Click and Change event not working for jquery-select2 options

查看:376
本文介绍了Click and Change事件不适用于jquery-select2选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery-select2库来实现我的下拉菜单.

I am using jquery-select2 library to implement my dropdowns.

就我而言,我希望能够在用户单击下拉列表中的选项后触发操作.但是,点击或更改事件似乎无效

In my case, I would like to be able to trigger an action after a user clicks on the option in the dropdown list. However, the click or change event doesn't seem to work

haml文件:

%select.medium.name_selector.pull_left
  %option.placeholder{value:"placeholder", disabled: "disabled", selected: "selected"} Start or find a conversation with a muser
  %option{value: "nick"} nick
  %option{value: "sam"} sam
  %option{value: "john} john

咖啡脚本文件:

events:
  "click option" : "displayChatScreen"

displayChatScreen: (e) ->
  e.preventDefault()
  nickname = @$("select.name_selector option:selected").val()
  if nickname != "placeholder"
    Backbone.history.navigate "messages/#{nickname}",
      trigger: true
  else
    alert "You need to select a friend to chat"

更改我的select2下拉框的选项后,是否仍有触发操作的机会?

Is there anyway to trigger the action once I change the option of my select2 dropdown box?

注意:我已经尝试了点击和更改事件,但它们都没有作用

Note: I have tried both click and change events and they both do not work

推荐答案

使用select2不能像使用普通<select>小部件那样使用普通change事件,但是实际上您需要附加由select2提供的 change处理程序.

With select2 you can't use the normal change event as you would for a normal <select> widget, but you actually need to attach your displayChatScreen method to the change handler provided by select2.

例如

$('select.medium.name_selector').on('change', this.displayChatScreen);

假设这是select2小部件的选择器,并且您正在适当的上下文中运行它.

Assuming that's the selector for your select2 widget and you're running that in the appropriate context.

当您使用Backbone提供的默认events哈希时,您实际上是在这样做:

When you use the default events hash provided by Backbone, you're really doing this:

$el.on('change', 'option', this.displayChatScreen);

由于select2实际上替换了<select>(因此将<option>标记替换为<ul> <li>对),因此您将永远不会真正收到浏览器事件.

Since select2 actually replaces the <select> (and therefore <option> tags with a <ul> <li> pair) you'll never actually receive the browser event.

此外,change事件在父级<select>而不是<option>元素上触发.

Additionally, the change event fires on the parent <select> not the <option> element.

这篇关于Click and Change事件不适用于jquery-select2选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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