如何在jQuery代码上实现jQuery live()?

时间:2016-08-19 11:39:16

标签: javascript jquery

我有以下jQuery代码:

$('.carousel[data-type="multi"].item').each(function(){
        var next = $(this).next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone(true).appendTo($(this));

        for (var i=0;i<2;i++) {
            next=next.next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }

            next.children(':first-child').clone(true).appendTo($(this));
        }
    });

如您所见,代码正在克隆轮播滚动上的元素。

问题是元素上的事件(jQuery .hide().show())没有被触发,因为克隆没有克隆数据事件。我尝试设置clone(true),但这不起作用。它在克隆发生之前(滚动之前)但在之后不起作用。在其他地方,我读到某人修复了.live()的类似问题,但我不知道如何在此处实施.live()。任何jQuery / Javascript大师?

1 个答案:

答案 0 :(得分:1)

AFAIK live已被弃用,您应该使用on .. ..

根据评论,hide()show()命令不起作用,因为动态添加的DOM元素不会触发click事件。

要解决此问题,您可以使用on

$('.carousel').on('click', '.item', function(e) {
    var $this = $(e.target); // should reference the `.item`

    //... perform the click event here for every item
});

现在,click事件附加到包含可点击项的元素,因此您可以在容器中添加和删除元素,而类名为item的项将触发事件。