简体   繁体   English

无法通过javascript创建元素的onmouseover属性

[英]Cannot create onmouseover attribute of an element by javascript

Tried to add by javascript: 试图通过javascript添加:

 var anc=document.createElement('a')
 anc.onmouseover="aFunc(1)"
 document.body.appendChild(anc)  

 function aFunc(b){ a=b/7 }

but cannot give or create any onmouseover attribute of such element 但不能提供或创建此类元素的任何onmouseover属性
How to do so correctly to solve such problem? 如何正确解决此类问题?

  var anc=document.createElement('a'); anc.innerHTML="aFunc(1)"; anc.setAttribute('onmouseover', 'aFunc(1)'); document.body.appendChild(anc); function aFunc(a) { alert('mouseover ' + a); } 
 <body> </body> 

You need to implement a listener on that object: 您需要在该对象上实现一个侦听器:

anc.addEventListener("mouseover", function( event ) {   
  // for example, I am changing the element color to yellow
  event.target.style.color = "yellow";
}, false);

More details can be found on MDN 可以在MDN上找到更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM