如果字符串包含"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
包含 a "
,这将关闭该属性,从而导致无效的 HTML。如果字符串包含Check this out.
没有任何引号,则最终结果仍然无效,原因有:
<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;