2016-01-02 142 views
0

我有一个按钮,当我按下按钮时需要创建更多按钮。单击按钮创建按钮

这是我为按钮写着:

<div class="response-container" id="response-container"> 
    <a href="#" class="button add-button" id="add-button">Add button</a> 
</div> 

我努力学习Backbone.js的,所以我写了一个视图中单击添加按钮时,创建更多的按钮。

createButton = Backbone.View.extend({ 
    events: { 
     'click .add-button': 'add_script' 
    }, 
    add_script: function() { 
     console.log('Pressed'); 
     //create a new button from here? 
    } 
}); 

任何人都可以帮助我做到这一点吗? console.log('Pressed')甚至不起作用。我正在尝试学习Web开发,有没有任何文件可以建议我?我欢迎所有的建议在Backbone.js

+0

请你要么清理您的HTML或张贴整个事情?我不确定那里发生了什么 – birdoftheday

+0

它应该是这样的......事件:{ “click.add-button”:“add_script” }, – vrn53593

+0

解释我们这是什么意思['click .add-script-button':'add_script']在你的代码中@waterkinq – vrn53593

回答

1

您必须创建视图的对象。 像这样

var createButton = Backbone.View.extend({ 
    el: '#response-container', 
    events: { 
     'click .add-button': 'add_script' 
    }, 

    initialize: function() { 
     console.log("initialized"); 
    }, 
    add_script: function() { 
     console.log('Pressed'); 
     //create a new button from here? 

    this.$el.append('<input type="button" value="new button"/>'); 


    } 
}); 

var cb = new createButton();

这里是DEMO

+0

这就是谢谢你,我不知道初始化函数是必要的。谢谢你的工作 – waterkinq

+0

我没有必要让你明白当我们通过new创建视图的对象时,视图的初始化方法被调用。 – Ajey

1

你如何努力实现这是不是最佳实践(因为这应该通过模板完成),但你可以这样做: 拳头,你必须在你的定义EL元素的例子case el:'#response-container'

events: { 
     'click #add-button': 'add_script' 
    }, 
    add_script: function() { 
     console.log('Pressed'); 
     //if you have el 
     this.$el.append('<input type="button" value="new button"/>'); 
     //or as jquyer add element 
     var r= $('<input type="button" value="new button"/>'); 
      $("body").append(r); 
    } 
+1

我真的不明白他怎么能让脚本工作,当他的事件是错误的,而不是使用类.add-button,他试图调用.add脚本按钮,我错了吗? – vrn53593