特定のスライドをターゲットとする要素をクリックした後に発生する Twitter ブートストラップ カルーセル .on(slid) イベントと、別の要素 (閉じるボタン) をクリックした後に発生する .on(slid) イベントがあります。ただし、2 番目のイベントが発生すると、最初の on(slide) イベントでも引き続き発生します。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/
私は何を間違っているのでしょうか?
ありがとう!
編集:イベントのネストについて、SO の他の場所でいくつかの議論を目にします。いずれにせよ、まだ複数のイベントが発生しているようです。イベント委任に live() を使用することは有望に見えます。ただし、すべてが混乱し始めているため、フィードバックを使用することはできます。