简体   繁体   中英

Uncaught TypeError: Cannot read property 'pageX' of undefined

I am tinkering with touchevents in js. I have encountered this error in my logcat in eclipse.

document.getElementById("squareBracket").
    addEventListener("touchmove", touchHandler, false);
document.getElementById("squareBracket").
    addEventListener("touchend", touchHandler, false);

function touchHandler(e) {
 if (e.type == "touchstart") {
 alert("You touched the screen!");
  } else if (e.type == "touchmove") {
 // alert(e.changedTouches[0].pageX);
 // alert(e.changedTouches[0].pageY);
 } else if (e.type == "touchend" || e.type == "touchcancel") {
  alert('X :' + e.targetTouches[0].pageX); 
  alert('Y :' + e.targetTouches[0].pageY);
}
}

If I remove the comment in the if in touchmove , the coordinates popup. However, if it is commented, the error in my logcat appears.

You should start understanding the difference of targetTouches, changedTouches and touches here: Variation of e.touches, e.targetTouches and e.changedTouches

in your case in the moment of touchend or touchcancel the targetTouches list is empty and the information remains in changedTouches.

changing your code to:

alert('X :' + e.changedTouches[0].pageX); 
alert('Y :' + e.changedTouches[0].pageY);

should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM