[英]Call javascript function from .innerHTML href
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. 我正在通过使用javascript函数调用其id来更改页面上的P元素,并且尝试从.innerHTML的HREF调用另一个名为closeWindow的javascript函数,如下所示。
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. 但是,javascript:closeWindow没有得到调用,或者我应该说甚至根本没有被读取,并且该函数失败。
Any suggestions would be appreciated 任何建议,将不胜感激
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? 如何给javascript函数提供这样的变量?
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. myvar可以工作,但是我无法提供一些文字。
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. 请一些帮助,我收到错误参考错误:未定义sometext。 It thinks sometext is a variable.
它认为某文本是一个变量。 Putting sometext in double quotes is resulting to an empty field after the comma 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>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.