JavaScript class構文
class構文の練習しているのですが、どこが問題なのかわからず...
nect,prevのボタンを押すと画像が切り替わる処理です。
⇒ handleEventでのthisの参照先変更
発生している問題・エラーメッセージ
Uncaught TypeError: this.next is not a function
該当のソースコード
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <style> * { margin: 0; padding: 0; } .wrapper { width: 350px; } .button_area { background-color: #000; height: 100px; display: flex; justify-content: center; } .button_area div { align-self: center; } .button_area div + div { margin-left: 20px; } .image_wrapper { display: flex; height: 200px; } .none { display: none; } </style> <div class="wrapper"> <figure class="image_wrapper"> <img src="https://fakeimg.pl/350x200/ff0000/?text=1"> </figure> <div class="button_area"> <div class="prev"><img src="https://fakeimg.pl/50x50/?text=prev"></div> <div class="next"><img src="https://fakeimg.pl/50x50/?text=next"></div> </div> </div> <script> class Photoview { constructor( init_index = 0 ){ this.$el = $('.image_wrapper img'); this.images = [ 'https://fakeimg.pl/350x200/ff0000/?text=1', 'https://fakeimg.pl/350x200/ff0000/000?text=2', 'https://fakeimg.pl/350x200/ff0000,128/000,255?text=3' ]; this.$nextBtn = $('.next'); this.$prevBtn = $('.prev'); this.index = init_index; this.handleEvent(); this.displayImg(); } get Index() { return this.index; } set Index( v ) { this.index = v; } handleEvent() { const self = this; this.$nextBtn.on("click", function(){ self.next( self.Index ); }); this.$prevBtn.on("click", function(){ self.prev(); }); } next() { this.index++; this.displayImg( this.Index ); } prev() { this.index--; this.displayImg( this.Index ); } displayImg() { this.$el.attr( 'src', this.images[ this.Index ] ); } } const Photoview_ins = new Photoview(); </script> </body> </html>
試したこと
いろいろ、ネットで調べてはみましたが解決に至らず...
回答2件
あなたの回答
tips
プレビュー