EventListener失败了长代码,为什么?

时间:2011-10-13 18:15:11

标签: javascript html

它应该填补该领域,但它没有做任何事,为什么?

<html>


<input type="button" id="phoneButton">
<input type="text" id="allQuery">


<script>
  // catch CLICKING with mouse to fill the text field
  var input = document.getElementById('phoneButton')
  input.addEventListener('click', function(e) 
  {
    document.getElementById('allQuery').value = 'hello' 
  }, false)


</script>

</html>

[更新] ...我的观点不是错字,我有更多这样的代码,但是更长,并且由于某种原因,这样的addEventListeners没有注意到它们与之一起使用的对象(例如phonebutton)。更长的代码有什么问题?如何确保eventListeners已经加载了vars,以便它们不会被长代码从缓存中清除?

4 个答案:

答案 0 :(得分:3)

getElementByIddocument的方法,而不是全局函数。

还要确保Javascript运行时存在#phonebutton元素; DOMContentLoaded事件通常很有帮助。

答案 1 :(得分:0)

嗯,你应该做document.getElementById('allQuery').value = 'hello'

答案 2 :(得分:0)

尝试保持正确的HTML格式

<html>
<head></head>
<body>
<input type="button" id="phoneButton">
<input type="text" id="allQuery">


<script type="text/javascript">
  // catch CLICKING with mouse to fill the text field
  var input = document.getElementById('phoneButton')
  input.addEventListener('click', function(e) 
  {
    document.getElementById('allQuery').value = 'hello'; 
  }, false);


</script>
</body>
</html>

答案 3 :(得分:0)

addEventListener不适用于所有浏览器。我建议使用js平台,它通过jquery等浏览器抽象事件绑定的不一致性。