在Mustache JS中生成按钮时,单击事件/绑定事件在jQuery中不起作用

时间:2016-09-30 13:59:11

标签: javascript jquery mustache

我有一个通过胡子JS模板在函数中生成的按钮。

{{#attributes}}
    <a class="button--small btn" data-selector="{{selector}}">{{title}}</a>
{{/attributes}}

,其示例输出为

<a class="button--small btn" data-selector=".news">More News</a>

但是,我在点击此按钮时尝试执行另一个jquery功能,但无论我使用.click(function() { });还是.bind,它似乎都不起作用?即使是console.log也不打印,所以我没有进入正确的条件。

这是脚本:

function lazyload(selector) {
    $("a[data-selector^='"+selector+"']").bind("click", function(e) {
            e.preventDefault();
            loadNews(selector);
    });
}

$(document).ready(function(){
   lazyload(".news"); // CALL FUNCTION READY FOR USAGE
});

1 个答案:

答案 0 :(得分:2)

对于新创建的元素,您需要委派event:请参阅&#34;直接和委派事件&#34;部分。

function lazyload(selector) {
   $(document).on("click", "a[data-selector^='"+selector+"']", function(e) {
        e.preventDefault();
        loadNews(selector);
   });
 }