文字列に"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が生成されます。文字列に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>';
この種の間違いを犯しやすいため、この方法でイベントを添付することはお勧めしません。むしろ、HTMLではなくDOM要素にイベントハンドラーを割り当てます。
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;