无法访问DOM对象属性

时间:2017-07-26 21:16:25

标签: javascript

我在表单中创建了一个包含所有输入元素的数组,然后循环遍历数组并尝试通过数组访问DOM元素对象。但它给出了错误“无法读取属性'addEventListener'的null”

 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>

4 个答案:

答案 0 :(得分:0)

使用forEach

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

答案 1 :(得分:0)

使用forEach()

  

forEach()按升序为数组中的每个元素执行一次提供的回调。对于已删除或未初始化的索引属性(即在稀疏数组上),不会调用它。

除了使用forEach()之外,我还包括了另一个重要的修复方法;

  • 使用addEventListener()收听元素focus时,我们将事件类型说明为“focusonfocus”。
  • 如果您不希望在<input type="submit">按钮获取focus时显示帮助提示,我们可以使用querySelectorAll()中的:not() pseudo-class对其进行过滤。
  • 您可能希望包含一些处理以避免帮助笔记在您的表单中倍增;目前,每次添加一个,任何已经存在的东西仍然存在;它会变得非常拥挤!

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
}

答案 2 :(得分:0)

首先使用document.addEventListener而不是window.addEventListener事件DOMContentLoaded适用于文档,在输入中使用class之后,对输入执行var到getid,你的代码应该是这样的:

 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>

答案 3 :(得分:0)

使用document.querySelectorAll('.form-container p input:not([type="submit"])')来阻止选择提交按钮(它失败,因为它没有id属性)。

同时写下focus代替onfocus