3

我正在学习主干,但我坚持为 html 选项元素绑定 onchange 事件。

我尝试使用“change”或“change #id”绑定,但这些都没有触发。但是,'click' 和 'click #id' 事件都有效。

<div id='target'>
    <select id='abc'>
        <option value=1>1</option>
        <option value=2>2</option>
    </select>
</div>
<input type='radio' name='def' value='1' checked>1</input>
<input type='radio' name='def' value='2'>2</input>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>

<script>
$(function () {
    var TargetView = Backbone.View.extend({
        el: '#target',
        events: {
            'click #abc': 'onclick',
            'click input[name=def]': 'onclick',
            'change': 'onselect',
            'change input[name=def]': 'onselect',
            'change #abc': 'onselect'
        },
        onclick: function (evt) {
            console.log('click');
            console.log($(evt.currentTarget).val());
        },
        onselect: function (evt) {
            console.log('change');
        }
    });
    new TargetView();
});
</script>
4

1 回答 1

2

我认为目前无法使用 Backbone 指定下拉菜单的 onChange onSelect 事件。

解决方法是直接使用jQuery

var view = Backbone.View.extend({
    initialize:function () {
        // on click is ok
        this.model.on('click', this.click, this);
        // cannot bind using backbone events change for some reasons, have to use jquery to setup the event
        $('input[name="my-dropdown"]', this.el).on('change', $.proxy(this.onselect, this));
    }
);
于 2013-06-07T01:37:57.437 回答