[英]JavaScript addEventListener not working?
I've created an variable which is selecting an Id of #bio , i'm then alerting the bio and getting a value of null. 我创建了一个变量,该变量选择一个#bio的ID,然后提醒该bio并获取null值。
I'm then adding an addEventListener to the bio variable and adding a focus and input to it, which should run a function called updateCounter();, every time the input box is foucessed on 然后,我在生物变量中添加addEventListener,并向其添加焦点和输入,每次输入框出现问题时,该焦点都应运行一个名为updateCounter();的函数。
The problem is the updateCounter isnt running. 问题是updateCounter没有运行。 I'm getting no errors in chrome.
我在Chrome中没有任何错误。 Could anyone provide a solution and explain where i'm going wrong please ?
任何人都可以提供解决方案并解释我要去哪里哪里吗?
var bio = document.getElementById('#bio'); // <textarea> element alert(bio); addEventListener(bio, 'focus', updateCounter); // Call updateCounter() on focus addEventListener(bio, 'input', updateCounter); // Call updateCounter() on input function updateCounter(e) { alert('Update Counter ran'); }
<input name="title-input" id="bio" type="text" placeholder="Insert Title" />
Aside from some syntax errors, the main reason it's not working is because .addEventListener()
is a method that operates on a DOM element. 除了某些语法错误外,它不起作用的主要原因是因为
.addEventListener()
是一种在DOM元素上运行的方法。
Therefore you need to change: 因此,您需要更改:
addEventListener(bio, 'focus', updateCounter);
addEventListener(bio, 'input', updateCounter);
to: 至:
bio.addEventListener('focus', updateCounter);
bio.addEventListener('input', updateCounter);
In addition, you don't need to include the #
character in the .getElementById()
method: 此外,您无需在
.getElementById()
方法中包含#
字符:
var bio = document.getElementById('bio'); bio.addEventListener('focus', updateCounter); bio.addEventListener('input', updateCounter); function updateCounter(e) { console.log('Logging to the console.'); }
<input name="title-input" id="bio" type="text" placeholder="Insert Title"/>
You've written vanilla JavaScript here, not jQuery. 您在此处编写的是普通JavaScript,而不是jQuery。
However, this is a simple fix: you pass the id
without #
to document.getElementById
. 但是,这是一个简单的解决方法:将没有
#
的id
传递给document.getElementById
。 You can fix this by adjusting your selection to be: document.getElementById('bio')
. 您可以通过将选择范围调整为
document.getElementById('bio')
来解决此问题。 You'll also want to be more explicit: make it bio.addEventListener('focus', updateCounter);
您还需要更加明确:将其设置为
bio.addEventListener('focus', updateCounter);
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.