单击按钮创建一个按钮

时间:2016-01-02 16:30:01

标签: javascript backbone.js

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

这是我为按钮编写的内容:

<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')甚至不起作用。我正在尝试学习网络开发,所以,有什么文件可以建议我吗?我很欢迎Backbone.js中的所有建议

2 个答案:

答案 0 :(得分:1)

您是如何尝试实现这一点并非最佳做法(因为这应该通过模板完成)但您可以这样做: 你必须在你的案例中定义el元素示例:&#39; #response-container&#39;

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 :(得分: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

相关问题