无法在动态添加的元素上启动脚本

时间:2013-09-02 06:52:18

标签: jquery html

这与此处的问题几乎相同:Click event doesn't work on dynamically generated elements,但该帖子已有几年了,而且它的解决方案对我不起作用。

我有一个小图片轮播,当我直接将其添加到html时可以正常工作,但是当我动态添加它时,按钮的jQuery click事件不起作用。我尝试从button.click()更改为button.on("click,function(){}),但仍然无效。有人能告诉我 a)如何使其工作 b)modyfying DOM如何影响jQuery执行,所以我将来会更好地理解它(例如,是否有一些DOM元素jquery忽略?)

我的代码:

$(document).ready(function(){
    $(".carousel-button-left").on('click',function(){
    var $ul=$(this).next().find(".carouselUl");;
    //alert(""+$ul.html());
    var $lastchild=$ul.children().last();
    $ul.prepend($lastchild);
    });
});


$(document).ready(function(){
    $(".carousel-button-right").on("click",function(){
    var $ul=$(this).prev().find(".carouselUl");
    //alert(""+$ul.html());
    var $firstchild=$ul.children().first();
    $ul.append($firstchild);
    });
});

3 个答案:

答案 0 :(得分:3)

尝试改变:

$(".carousel-button-left").on('click',function(){
...

$(document).on('click', '.carousel-button-left', function(){
...

以便jQuery接收事件并将其委托给与作为参数提供的选择器匹配的元素。

答案 1 :(得分:1)

使用事件委派来为动态添加的元素注册处理程序。

仅使用.on()不会使事件注册委派成为基础,附加处理程序的参数和元素很重要

$(document).ready(function () {
    $(document).on('click', ".carousel-button-left", function () {
        var $ul = $(this).next().find(".carouselUl");;
        //alert(""+$ul.html());
        var $lastchild = $ul.children().last();
        $ul.prepend($lastchild);
    });
});

$(document).ready(function () {
    $(document).on("click", ".carousel-button-right", function () {
        var $ul = $(this).prev().find(".carouselUl");
        //alert(""+$ul.html());
        var $firstchild = $ul.children().first();
        $ul.append($firstchild);
    });
});

执行脚本时,在dom中应该添加处理程序的元素集(.on()调用的LHS),然后我们需要在.on()中使用第二个参数调用以指定LHS元素下存在的目标元素选择器。

答案 2 :(得分:0)

尝试

$(document).ready(function(){
    $(document).on('click',".carousel-button-left",function(){
    var $ul=$(this).next().find(".carouselUl");;
    //alert(""+$ul.html());
    var $lastchild=$ul.children().last();
    $ul.prepend($lastchild);
    });
});


$(document).ready(function(){
    $(document).on("click",".carousel-button-right",function(){
    var $ul=$(this).prev().find(".carouselUl");
    //alert(""+$ul.html());
    var $firstchild=$ul.children().first();
    $ul.append($firstchild);
    });
});