hyperlink - Javascript onclick in script -


OK I'm new to javascript, but I add onclick = "function ()" without anchor to an onclick function I want to call the tag. Here's my script, but I can not do it for work:

  & lt; Script type = "text / javascript" & gt; Function click () {alert ("hi"); } Document.getElementById ('click'). Onclick = clicka; & Lt; / Script & gt; & Lt; A href = "#" id = "click" & gt; Click & lt; / A & gt;  

When I click on the link, it should "Hi", any ideas should be alerted?

Place either the script after the a tag or window Wrap the script inside the .onload function. Any of these will work:

  & lt; Script type = "text / javascript" & gt; Window.onload = function () {function clicka () {warning ("hi"); return false; } Document.getElementById ('click'). Onclick = clicka; } & Lt; / Script & gt; & Lt; A href = "#" id = "click" & gt; Click & lt; / A & gt;  

or:

  & lt; A href = "#" id = "click" & gt; Click & lt; / A & gt; & Lt; Script type = "text / javascript" & gt; Function click () {alert ("hi"); return false; } Document.getElementById ('click'). Onclick = clicka; & Lt; / Script & gt;  

The reason for this does not work is that you are bound to the click event of the a tag before the a tag exists; So it is not getting any element and nothing will do anything.

Insert the script inside the window. Download You are given the instructions to run the script only after all the elements are loaded and the element can be found.

To prevent the browser from actually redirecting to # , you can return from your clicka function I've marked up.


Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -