我在 JavaScript 函数内有一个 JavaScript 函数。下面的 JavaScript 使用 getElementbyID
在 div
中插入一些 HTML。
它正在传递一个变量,好吧——这似乎是一个对象的子对象,this.value
——顺便说一句,我是一个 JavaScript 新手,但是,当我尝试给它另一个变量时要传递的变量,由 l
表示的字符串将停止工作。下面的type 1
尝试传递变量l
不起作用,否则可以。我也刚刚尝试放置 l '+
但这不起作用。谁能帮助我使用传递变量的正确语法?谢谢。
if (type==1)
{
var mailbox = '<form action="mail.php" method="post"><input type="text" onkeyup="showResult(this.value,'+l+')"><input type="submit" name="submit" value="Email"><div id="livesearch"></div></form>';
}
else
{
var mailbox = '<form action="share.php" method="post"><input type="text" onkeyup="showResult(this.value)"> Share<div id="livesearch"></div></form>';
}
document.getElementById(target).innerHTML = mailbox;
return false;
}
最佳答案
如果字符串包含带有双引号的“Check this out.”
,则生成的 HTML 标记将如下所示(添加了格式设置):
<form action="mail.php" method="post">
<input type="text" onkeyup="showResult(this.value,"Check this out.")">
<input type="submit" name="submit" value="Email">
<div id="livesearch"></div>
</form>
请注意 onkeyup
的属性值如何包含 "
,这会关闭该属性,导致 HTML 无效。如果字符串包含 ,请检查一下.
没有任何引号,最终结果仍然无效,还有一个原因:
<form action="mail.php" method="post">
<input type="text" onkeyup="showResult(this.value,Check this out.)">
<input type="submit" name="submit" value="Email">
<div id="livesearch"></div>
</form>
在本例中,showResult(this.value,Check this out.)
是事件处理程序 JavaScript,并且存在语法错误。您想要的是将字符串放在单引号中,这样它就不会破坏属性,因此它是有效的 JavaScript:
var mailbox = '<form action="mail.php" method="post"><input type="text" onkeyup="showResult(this.value,\''+l+'\')"><input type="submit" name="submit" value="Email"><div id="livesearch"></div></form>';
请注意,不建议以这种方式附加事件,因为很容易犯这种类型的错误。相反,将事件处理程序分配给 DOM 元素,而不是 HTML:
var mailboxHtml;
var keyUpHandler;
if (type==1)
{
mailboxHtml = '<form action="mail.php" method="post"><input type="text" id="search"><input type="submit" name="submit" value="Email"><div id="livesearch"></div></form>';
keyUpHandler = function() { showResult(this.value, l); };
}
else
{
mailboxHtml = '<form action="share.php" method="post"><input type="text" id="search"> Share<div id="livesearch"></div></form>';
keyUpHandler = function() { showResult(this.value); };
}
document.getElementById(target).innerHTML = mailbox;
document.getElementById('search').onkeyup = keyUpHandler;
return false;
关于javascript中的javascript,传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954923/