2

html file

<div class="work">
    <ul id="palette" class="palette-pen" style="top:178px;"> 
        <li class="palette-colour-1"><span></span></li>
        <li class="palette-colour-2"><span></span></li>
        <li class="palette-colour-3"><span></span></li>
        <li class="palette-colour-4"><span></span></li>
        <li class="palette-colour-5"><span></span></li> 
        <li class="palette-colour-6"><span></span></li>
    </ul>
</div>

js file

VC.View.Workspace_Tool_Image = Backbone.View.extend({
    events : {  
        'click .palette-pen li' : 'paint'
    },

    initialize : function() {
        var obj = this;

        /* scope */
        _.bindAll(this, 'paint');
    },

    paint: function() {
        var obj = this;
        $('ul.palette-pen li').click(function(e) { 
            alert(obj.$el.attr('class'));
        });
    },
})

I want to get the class of the specific li that I clicked, but when I click on an li the 1st time then it gives no alert. When I click a second time, it gives 1 alert with the div's class(work) rather than the class of the li that I clicked.

If I clicked on li nth time then it gives me n-1 alert. Why does this happen? Whether I clicked single time whether it is nth time or 7th time, it must give only one alert.

So please help me to find out the solution.

4

1 回答 1

3

似乎每次单击时,您都会添加一个显示警报的单击侦听器。所以结果是有道理的。由于“paint”仅在您单击时被调用,因此只需将您的警报直接放在其中:

paint : function(e) {
    alert($(e.currentTarget).attr('class'));
},
于 2013-05-10T12:52:31.473 回答