【问题标题】:My update.js.erb file only runs on the first button click and not on subsequent clicks (change a button's class and value on click)我的 update.js.erb 文件仅在第一次单击按钮时运行,而不是在后续单击时运行(单击时更改按钮的类和值)
【发布时间】:2015-03-26 11:40:25
【问题描述】:

我有一个待办事项列表应用程序,其中包含一个完成/未完成任务按钮。我想在单击它时在使按钮类和按钮值更改之间切换。我得到了更改第一次单击的按钮,但随后单击同一按钮不会更改该按钮。我检查了我的日志并在第一次单击后调用了 todo#update 方法,但在第一次单击后它似乎没有在 update.js.erb 中运行我的 JavaScript 代码。

在我的 update.js.erb 文件中:

// change color
$("#todo-button-<%=@todo_id%>").attr('class', "<%=button_class%>");

// change button text
$("#todo-button-<%=@todo_id%>").attr('value', "<%=button_status%>");

这是 index.html.erb 中的按钮

<%= button_to button_status,
    update_todo_path( todo_id: todo["id"],
                      description: todo["description"],
                      is_complete: todo["is_complete"]
                      ),
    remote: true,
    class: "#{button_class}",
    id: "todo-button-#{todo["id"]}"%>

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby erb


    【解决方案1】:

    我最终通过使用点击功能解决了这个问题。我的代码比我想要的更冗长但有效:

    $('.todo-button').click(function(){
        if($(this).hasClass("btn-primary")){
            $(this).removeClass("btn-primary");
            $(this).addClass("btn-success");
            $(this).val("Incomplete");
        }else  if($(this).hasClass("btn-success")){
            $(this).removeClass("btn-success");
            $(this).addClass("btn-primary");
            $(this).val("Complete");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      相关资源
      最近更新 更多