简体   繁体   English

无法在Java脚本中单击图像的事件时调用函数

[英]unable to call a function on click Event of an image in java script

I have defined a Variable containing the Image in a java script file 我已经在Java脚本文件中定义了一个包含Image的变量

 var route ='<img src="http://s31.postimg.org/mwewcja1j/146117012724825.png" alt="route" id="routeimg" onclick="myFunction()" style="width:50px;height:35px;">';
 function myFunction{alert("hello")}

Error myFunction is not defined. 错误myFunction未定义。

or 要么

 var route ='<img src="http://s31.postimg.org/mwewcja1j/146117012724825.png" alt="route" id="routeimg" style="width:50px;height:35px;">';
document.getElementById("routeimg").onclick= "alert("hello")";

Error :routeimg is not defined

I have googled for all posts of this type & replicated the Exact Procedure but nothing helped me out 我已经用Google搜索了所有此类帖子并复制了“确切程序”,但没有任何帮助

Your function has incorrect syntax. 您的函数语法错误。 It's missing the parentheses: 它缺少括号:

function myFunction(){
    alert("hello")
}

For this to work, your route has to be added to the DOM of course. 为此,必须将您的route添加到DOM中。

The second code snippet will fail for a different reason. 第二个代码段将因其他原因而失败。 Whilst parsing the HTML document converts a tag attribute value of onclick="alert('hello')" into a HTML event handler function of form 解析HTML文档时,会将标记属性值onclick="alert('hello')"转换为以下形式的HTML事件处理函数:

function(event){ onclick_attriute_text_from_HTML_source };

and adds it as the onclick property of the HTMLelement created for the tag in the DOM, you can't set the attribute to text in code. 并将其添加为在DOM中为标记创建的HTMLelement的onclick属性,则无法在代码中将属性设置为text。 It must be set to a function object instead. 必须将其设置为功能对象。 EG 例如

document.getElementById("routeimg").onclick= function(){alert("hello")";};

As before, you must have added the element to the DOM first. 和以前一样,您必须先将元素添加到DOM。

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

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