admin管理员组

文章数量:1410697

I am altering a P element on a page by calling it's id with a javascript function and I am trying to call another javascript function called closeWindow from the HREF of a .innerHTML like below.

document.getElementById("link").innerHTML = "<p>You may close this window <a href="javascript:closeWindow();">here</a></p>"

However the javascript:closeWindow is not getting called or I should say is not even being read at all and the function fails.

Any suggestions would be appreciated

I am altering a P element on a page by calling it's id with a javascript function and I am trying to call another javascript function called closeWindow from the HREF of a .innerHTML like below.

document.getElementById("link").innerHTML = "<p>You may close this window <a href="javascript:closeWindow();">here</a></p>"

However the javascript:closeWindow is not getting called or I should say is not even being read at all and the function fails.

Any suggestions would be appreciated

Share Improve this question asked Mar 21, 2014 at 13:58 Alex McPhersonAlex McPherson 3,1953 gold badges32 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Your quotes are negating one another, as you can see in the code view. Use single quotes or escape your double quotes:

document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow();'>here</a></p>"

how about giving the javascript function some variables like this?

var myvar=123;
document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow("+myvar+",sometext);'>here</a></p>";

the myvar works, but i can't get sometext to work.

this did not work:

var mytxt='sometext'; 
var myvar=123;
    document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow("+myvar+","+mytxt+");'>here</a></p>";

Please some help, i get the error reference error: sometext is not defined. It thinks sometext is a variable. Putting sometext in double quotes is resulting to an empty field after the ma and a syntax error.

Found the answer:

var mytxt='sometext'; 
    var myvar=123;
        document.getElementById("link").innerHTML = "<p>You may close this window <a href='javascript:closeWindow("+myvar+",\""+mytxt+"\");'>here</a></p>";

本文标签: Call javascript function from innerHTML hrefStack Overflow