我有一个 Twitter 引导轮播 .on(slid) 事件,该事件在单击以特定幻灯片为目标的元素后触发,还有一个 .on(slid) 事件在单击不同元素(关闭按钮)后触发。但是,一旦发生第二个事件,即使第一个 on(slid) 事件也会继续触发。我认为 preventDefault() 会解决这个问题,但事实并非如此。我什至尝试了一个更完整的功能(如下所示,来自Herb Caudill)来做到这一点,但没有成功。
使用 (this) 将事件的范围绑定到函数不起作用。我对此很陌生,所以我认为这里可能有一个我没有掌握的基本概念。
这是我的代码的简化版本:
// Intended to prevent event bubble up or any usage after this is called.
eventCancel = function (e)
{
if (!e)
if (window.event) e = window.event;
else return;
if (e.cancelBubble != null) e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
if (window.event) e.returnValue = false;
if (e.cancel != null) e.cancel = true;
}
$('.recentContent').click(function(){
var $lastIndex = $('#splashCarousel .carousel-inner').children().last().getIndex();
$('#splashCarousel').carousel($lastIndex); //slide to specific index
$('#splashCarousel').carousel('pause');
$('#splashCarousel').on('slid', function (e) {
alert("open");
//do stuff
return eventCancel(e);
})
});
$('.closeX').click(function(){
var $lastItem = $('#splashCarousel .carousel-inner').children().last();
$('#splashCarousel').carousel(0);
$('#splashCarousel').on('slid', function (e) {
alert("close");
//do other stuff
return eventCancel(e);
})
});
这是一个更简单的小提琴尝试 preventDefault:http: //jsfiddle.net/chardwick/a5Dpe/
我可能做错了什么?
谢谢!
编辑:我在其他地方看到一些关于嵌套事件的讨论,它们不应该做,有时他们必须做。无论哪种方式,我似乎仍然会触发多个事件。使用 live() 进行事件委托看起来很有希望。尽管如此,仍然可以使用一些反馈,因为这一切都开始让我感到困惑。