문제

I've used backbone.js 'click' event here. onClick event, I want to select the clicked HTML element,remove it and add into added list.

I am not able to access all HTML dom element where I have clicked. After getting HTML element.

If I click 'China', The below code would alert '<li>China</li>'.

So, How do I access all dom properties ?

Java Script code:

var ActionBox = Backbone.View.extend({
        el:$("#container"),
        events: {
                    "click #add li": "addItem",
                    "click #alert": "alertHere"
        },
        initialize: function(){     
                _.bindAll(this,"addItem","render");             
                this.render();  
        },
        render:function(){  
                this.prepareActions();          
        },
        addItem:function(ev){
                var ac=$(ev.target).html(); // it doesn't give me "<li>US</li>" after clicking US
                alert(ac);
                },
        prepareActions:function(){          
                    var str="";
                    for(var i=0;i<actions.length;i++)   str+="<li>"+actions[i]+"</li>";                         
                    $("#add ul").append(str);
        }       
    });    
var actionBox = new ActionBox();

and HTML code as below:

    <div id="container">
    <table>
    <tr>
        <td>
            <div id="add">      
                <ul>
                 <li>US</li>
                 <li>China</li>
                 <li>UK</li>
                </ul>
            </div>
        </td>
        <td>
            <div id="controls">

            </div>
        </td>
        <td>
            <div id="added">        
                <ul></ul>
            </div>
        </td>
    </tr>
    </table>        
</div>

There are two ul containers, add and added, If I click the element from source, it should be shifted into target container.

도움이 되었습니까?

해결책

You just want to use appendTo - this will remove it and put it into your #added UL

$(ev.target).appendTo('#added');

다른 팁

I tried running it myself with Backbone 0.9.1, and everything worked fine. Make sure you're including

var ActionBox = Backbone.View.extend({
    el:$("#container"),
    ...      
});

after your HTML is rendered. Otherwise, you're specifying $("#container") before it actually exists in the DOM. If you do that, jQuery will return nothing therefore setting el to an empty array, so your events are will be bound to nothing... Therefore they'd never be called.

Here is a jsFiddle with it working: http://jsfiddle.net/8jyeb/1/ . Notice that you have to wrap all of the JavaScript in a jQuery DOM Ready handler. This will ensure the code isn't run until the HTML has loaded.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top