JavaScriptでクリックイベントのthis.idをStringに変えたい
JavaScriptで以下のようなコードを書いています。
型変換がうまくできておらず以下のエラーメッセージが発生しました。
文字型として、うまく扱うにはどのようにすればよいでしょうか?
発生している問題・エラーメッセージ
Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
該当のソースコード
JavaScript
1function clickEvt(){ 2 const getWindowScrollPosition = function() { 3 return { 4 x : (typeof window.scrollX !== 'undefined') ? window.scrollX : ((typeof document.documentElement.scrollLeft !== 'undefined') ? document.documentElement.scrollLeft : document.body.scrollLeft), 5 y : (typeof window.scrollY !== 'undefined') ? window.scrollY : ((typeof document.documentElement.scrollTop !== 'undefined') ? document.documentElement.scrollTop : document.body.scrollTop) 6 }; 7 }; 8 const position = getWindowScrollPosition(); 9 var eventID= this.id.toString(); 10 const eventNo= eventID.replace(/[^0-9]/g, ''); 11 eventID= 'position'+eventNo; 12 console.log(eventID); 13 document.getElementById(eventID).value = position['x']+','+position['y']; 14} 15const hoge = document.getElementsByClassName('clickEvent'); 16for (var i = 0; i < hoge.length; i++) { 17 hoge[i].addEventListener('click', clickEvt, false); 18}
試したこと
var eventID= this.id;
const eventNo= eventID.replace(/[^0-9]/g, '');
と初めはしたのですが、replaceを持たないと型のエラーとなっており。
文字型として渡してほしくthis.id.toString();としました。
間違っていたこと
スクリプトの対象となっていたHTML本文が間違っていました。
全て「pocition」となっておりJavaScriptでの指定の「position」ではエラーとなったようです。
回答1件
あなたの回答
tips
プレビュー