如果元素从一开始就不在页面中,则函数不响应

Function not responding if the element is not in the page from the start

我有这个功能:

$(function(){
    $(".todo-task").click(function(){
        $(".todo-task").css('background-color','green');
    });
});

问题是 "todo-task" 不是加载页面时出现的元素,而是使用其他功能附加到页面的元素。 我认为上面的事实阻止了我编写的功能的发生,因为如果我在页面中出现 "todo-task" 时将完全相同的功能粘贴到控制器中,一切都会完美无缺。

我该怎么办?

使用事件委托:

$(function(){
    $(document).on("click", ".todo-task", function(){
        $(".todo-task").css('background-color','green');
    });
});

请注意,document 可以 - 并且应该 - 替换为最初存在的最接近的父级(为了性能 - 当您知道它将在特定 div).