我的 update.js.erb 文件仅在第一次单击按钮时运行,而不在后续单击时运行(单击时更改按钮的类和值)

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)

本文关键字:单击 运行 按钮 erb js update 文件 我的 第一次      更新时间:2023-09-26

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

在我的更新.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"]}"%>

我最终通过使用单击函数来解决这个问题。 我的代码比我想要的更冗长,但有效:

$('.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");
    }
});