0

したがって、ドキュメント内のすべての要素でタッチイベントをリッスンするこの JavaScript コードがあります。

document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);

dataCard( ) のクラスのアイテムと、アンカーではないすべての子のイベントのみをリッスンしたい場合を除いて、これは問題なく機能します。.dataCard<a>

したがって、ページの前半でjQueryを使用しているため、jQueryセレクターを作成してそれを呼び出すことで、それを修正する方法を考えまし.addEventListener()た。それはうまくいきませんでした。

これは私が試したものです:

$('.dataCard, .dataCard *:not(a)').addEventListener("touchstart", touchHandler, true);
$('.dataCard, .dataCard *:not(a)').addEventListener("touchmove", touchHandler, true);
$('.dataCard, .dataCard *:not(a)').addEventListener("touchend", touchHandler, true);
$('.dataCard, .dataCard *:not(a)').addEventListener("touchcancel", touchHandler, true);

前に言ったように、それはうまくいきませんでした。jQuery と JS が時々うまく混ざらないからだと思います。

.dataCardここで、イベントをすべてのインスタンス(現在存在するもの、またはプログラムで作成される可能性があるもの)にも委任する必要があることに気付きました。

関数を使用して jQuery ソリューション全体を使用できるようになったので、これは良いことです.on()

これは私が試したものです:

$('#main').on('touchstart', '.dataCard', function(event){
    touchHandler(event);
});
$('#main').on('touchmove', '.dataCard', function(event){
touchHandler(event);
});
$('#main').on('touchend', '.dataCard', function(event){
touchHandler(event);
});
$('#main').on('touchcancel', '.dataCard', function(event){
touchHandler(event);
});

現在、#mainは安定しており、常に存在し.dataCardます。一部が存在し、一部がプログラムで追加されるのは s です。

したがって、イベント委任に関しては、これはうまく機能します。私の問題は、これも機能していないことです。

touchstarttouchmovetouchend、およびtouchcancelが認識できるjQueryイベントではないためだと思います。

だから私の質問は、コードの最初のブロックが行うこと(これらのタッチイベントのイベントリスナーを追加する)を.dataCard、jQueryまたはプレーン/バニラjsで存在し、プログラムで作成されたすべてのインスタンスに対してのみ行うにはどうすればよいですか?

4

2 に答える 2

1

event プロパティを使用して、targetそれが のインスタンスであるかどうかをテストでき.dataCardます。

$('#main').on('touchstart touchmove touchend touchcancel', '.dataCard', function(event){
    if($(event.target).is('.dataCard')) {
        touchHandler(event);
    }
});

実際のデモクリック ハンドラーも追加したので、デスクトップ ブラウザーでテストできます。

余談ですが、 の最初のパラメーターとしてスペース区切りのリストを指定することで、複数のイベント リスナーを同じハンドラーに登録できますon()

于 2013-08-07T16:06:21.227 に答える
0

.on()これを行うには、適切なセレクターを使用して配列パラメーターを送信します。

$(function() {
    $('.dataCard *:not(a)', '#main').on({
        touchstart: function() {
           console.log('touchstart');
        },
        touchmove: function() {
          console.log('touchmove');
        },
        touchend: function() {
          console.log('touchend');
        },
        touchcancel: function() {
          console.log('touchcancel');
        }
    });
});

これがjsFiddleです。

于 2013-08-07T16:38:59.127 に答える