[英]HTML element attached to JS object
我只是陳述了一些OOJS,但我無法解決一件事,為HTML元素創建對象並向其中添加事件。
為了練習起見,我有一個想法可以進行驗證,編輯等操作。
這是我如何調用輸入並將其分配給HTML對象的方法
var elements = document.querySelectorAll('.input-field');
for (var n = 0; n < elements.length; n++) {
var instance = new input(elements[n]);
}
這實際上有效,事件已分配
但是,當我單擊輸入this.element
未定義時,我真的不知道怎么做,因為我已經用this.element
的對象構造了該對象。
(function(){ 'use strict'; var Input = function Input(elem) { this.element = elem; this.construct(); }; Input.prototype.Classes = { INPUT: 'input-field__input', LABEL: 'input-field__label', EDITED: 'input-field--edited', FOCUSED: 'input-field--focused' }; Input.prototype.onFocus_ = function(e) { this.element.classList.add(this.Classes.FOCUSED); }; Input.prototype.construct = function() { if(this.element) { this.input = this.element.querySelector('.' + this.Classes.INPUT); this.label = this.element.querySelector('.' + this.Classes.LABEL); if(this.input){ this.input.addEventListener('focus', this.onFocus_); } } } var elements = document.querySelectorAll('.input-field'); for (var n = 0; n < elements.length; n++) { var instance = new Input(elements[n]); } })()
<div class="input-field"> <label class="input-field__label">Name</label> <input type="text" name="name" class="input-field__input"> </div> <div class="input-field"> <label class="input-field__label">Last</label> <input type="text" name="last" class="input-field__input"> </div>
問題在於事件是已分配的,但它不知道它是哪個對象, this
是指向實際的HTML輸入而不是Input
對象。
我該如何解決?
我在網上搜索,但找不到類似的內容。 我最近發現: 附加到HTML元素的JS對象
另外,如果您可以通過任何方式改進代碼,請不要介意我還在學習。
先感謝您
使用bind
函數定義函數將使用的范圍。 當前,您的范圍是您的元素,而不是您的類實例。
this.input.addEventListener('focus', this.onFocus_.bind(this));
(function(){ 'use strict'; var Input = function Input(elem) { this.element = elem; this.construct(); }; Input.prototype.Classes = { INPUT: 'input-field__input', LABEL: 'input-field__label', EDITED: 'input-field--edited', FOCUSED: 'input-field--focused' }; Input.prototype.onFocus_ = function(e) { this.element.classList.add(this.Classes.FOCUSED); }; Input.prototype.construct = function() { if(this.element) { this.input = this.element.querySelector('.' + this.Classes.INPUT); this.label = this.element.querySelector('.' + this.Classes.LABEL); if(this.input){ this.input.addEventListener('focus', this.onFocus_.bind(this)); } } } var elements = document.querySelectorAll('.input-field'); for (var n = 0; n < elements.length; n++) { var instance = new Input(elements[n]); } })()
<div class="input-field"> <label class="input-field__label">Name</label> <input type="text" name="name" class="input-field__input"> </div> <div class="input-field"> <label class="input-field__label">Last</label> <input type="text" name="last" class="input-field__input"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.