簡體   English   中英

無法訪問DOM對象屬性

[英]not able to access DOM object property

我創建了一個表單中所有輸入元素的數組,然后遍歷該數組,並嘗試通過該數組訪問DOM元素對象。 但它給出了錯誤“無法讀取null的屬性'addEventListener'”

 window.addEventListener("DOMContentLoaded", function() {
    var paraC = document.querySelectorAll('.form-container p input');

    for (var i = 0; i < paraC.length; i++) {

        var inputField = document.getElementById(paraC[i].getAttribute('id'));
        console.log(inputField); // gives null
        inputField.addEventListener('onfocus', helperNote, false);
    }




    function helperNote() {
        var notePlace = document.querySelector('.form-container');
        var note = document.createElement('p')
        notePlace.appendChild(note);
        console.log('event fired');
    }
}, false);

HTML代碼

<section>
            <h3>Sign-Up Form</h3>
            <form method="post">
                <div class="form-container">
                    <p>Fill The Form Below</p>
                    <p>
                        <label>Email :</label>
                        <input type="email" name="email" id="email">
                    </p>
                    <p>
                        <label>Name :</label>
                        <input type="text" name="Name" id="Name">
                    </p>
                    <p>
                        <label>Age :</label>
                        <input type="number" name="age" id="age">
                    </p>
                    <p>
                        <input type="submit" name="submit" value="sign-up">
                    </p>
                </div>
            </form>
        </section>

僅使用forEach會更簡單:

document.querySelectorAll('.form-container p input')
    .forEach(function(inputField) {
         inputField.addEventListener('onfocus', helperNote, false);
    })

使用forEach()

forEach()對數組中存在的每個元素以升序執行一次提供的回調。 對於已刪除或未初始化(即在稀疏數組上)的索引屬性,不會調用它。

除了使用forEach() ,我還包括另一個重要的修復程序;

  • 當使用addEventListener()偵聽元素focus我們將事件類型聲明為“ focus而不是onfocus ”。
  • 如果您不希望在<input type="submit">按鈕獲得focus時顯示幫助者注釋,則可以使用querySelectorAll():not()偽類將其過濾掉。
  • 您可能需要進行一些處理,以免輔助說明在表格中成倍增加。 當前,每次添加一個,就已經存在了; 可能會很擁擠!

 window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll('.form-container input:not([type=submit])') .forEach( function( inputField ) { console.log(inputField); inputField.addEventListener('focus', helperNote, false); } ); function helperNote() { var notePlace = document.querySelector('.form-container'); var note = document.createElement('p'); note.textContent = "Helper Note"; notePlace.appendChild(note); console.log('event fired'); } }, false); 
 <section> <h3>Sign-Up Form</h3> <form method="post"> <div class="form-container"> <p>Fill The Form Below</p> <p> <label>Email :</label> <input type="email" name="email" id="email"> </p> <p> <label>Name :</label> <input type="text" name="Name" id="Name"> </p> <p> <label>Age :</label> <input type="number" name="age" id="age"> </p> <p> <input type="submit" name="submit" value="sign-up"> </p> </div> </form> </section> 

有關代碼的一些指針

// the p is unnecessary
var paraC = document.querySelectorAll( '.form-container p input' );

// for elem at index until length
for (var i = 0; i < paraC.length; i++) {

    // the iterated array-like node list already contains references to the elements
    // paraC[i] is a reference to one of the elements
    // paraC[i].getAttribute('id') could be shortened to paraC[i].id
    // getting the id of the element in order to get the element is unnecessary.
    var inputField = document.getElementById(paraC[i].getAttribute('id'));

    // the submit input has no id but will be the last referenced input
    // the paraC[i].getAttribute('id') will return undefined
    // document.getElementById(undefined) is clearly not going to work well
    console.log(inputField); // gives null
}

首先使用document.addEventListener而不是window.addEventListener,該事件DOMContentLoaded適用於文檔,在輸入中使用類之后,對輸入的getid執行Var操作,您的代碼應如下所示:

  document.addEventListener("DOMContentLoaded", function() { var paraC = document.querySelectorAll('.yourclass'); for (var i = 0; i < paraC.length; i++) { var inputField = paraC[i], inputFieldId = inputField.getAttribute('id'); console.log(inputFieldId); inputField.addEventListener('focus', helperNote, false); } function helperNote() { var notePlace = document.querySelector('.form-container'); var note = document.createElement('p') notePlace.appendChild(note); console.log('event fired'); } }, false); 
 <section> <h3>Sign-Up Form</h3> <form method="post"> <div class="form-container"> <p>Fill The Form Below</p> <p> <label>Email :</label> <input class="yourclass" type="email" name="email" id="email"> </p> <p> <label>Name :</label> <input class="yourclass" type="text" name="Name" id="Name"> </p> <p> <label>Age :</label> <input class="yourclass" type="number" name="age" id="age"> </p> <p> <input type="submit" name="submit" value="sign-up"> </p> </div> </form> </section> 

使用document.querySelectorAll('.form-container p input:not([type="submit"])')可以防止選擇“提交”按鈕(由於它沒有id屬性,因此失敗了)。

還要寫focus而不是onfocus

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM