如何使用backbone js为函数动态传递diff参数?

elcex8rz  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(170)

这是我刚才玩的小提琴
fiddle
这是我的html

<div id="search_container">a</div>
<script type="text/template" id="search_template">
    <label>Search</label>
    <input type="text" id="search_input" />
    <input type="button" class="button" id="search_button" value="Search" />
     <input type="button" class="button" id="a" value="asfasd" />
     <input type="button" class="button" id="b" value="Seaasdasdrch" />
     <input type="button" class="button" id="c" value="Seadasdasdasrch" />
</script>

这是我的Javascript

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using underscore
        var template = _.template( $("#search_template").html(), {} );
        // Load the compiled HTML into the Backbone "el"
        this.$el.html( template );
    },
    events: {
        "click input[class=button]": "doSearch"  
    },
    doSearch: function( event ){
        // Button clicked, you can access the element that was clicked with event.currentTarget
       alert( "Search for " + $("#a").val() );
    }
});

var search_view = new SearchView({ el: $("#search_container") });

我想为一堆按钮调用同一个函数,但是我想根据它们的值为它们给予不同的参数。我如何克服并给予不同按钮唯一属性?
请帮帮我..!

bf1o4zei

bf1o4zei1#

如果我正确理解了您的问题,我认为您希望捕获以下按钮的不同值

<input type="button" class="button" id="search_button" value="Search" />
<input type="button" class="button" id="a" value="asfasd" />
<input type="button" class="button" id="b" value="Seaasdasdrch" />
<input type="button" class="button" id="c" value="Seadasdasdasrch" />

如果是这样,您可以将程式码修改为下列内容:

doSearch: function( event ){
    // Button clicked, you can access the element that was clicked with event.currentTarget
    alert( "Search for " + $(event.currentTarget).attr('value') );
}

相关问题