したがって、ドキュメント内のすべての要素でタッチイベントをリッスンするこの 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 です。
したがって、イベント委任に関しては、これはうまく機能します。私の問題は、これも機能していないことです。
touchstart
、touchmove
、touchend
、およびtouchcancel
が認識できるjQueryイベントではないためだと思います。
だから私の質問は、コードの最初のブロックが行うこと(これらのタッチイベントのイベントリスナーを追加する)を.dataCard
、jQueryまたはプレーン/バニラjsで存在し、プログラムで作成されたすべてのインスタンスに対してのみ行うにはどうすればよいですか?