简体   繁体   中英

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

 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.

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

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.

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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