0

JavaScript関数内にJavaScript関数があります。div以下のJavaScriptは、 usingにHTMLを挿入しgetElementbyIDます。

1つの変数を渡していますが、これはオブジェクトの子のようthis.valueです。--btw、私は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;
}
4

2 に答える 2

3

文字列に"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;
于 2012-06-08T19:41:50.677 に答える
0

が文字列の場合l、レンダリングされたコードで文字列のように見えるようにする必要があります。

これに使用できますJSON.stringify()(実際、オブジェクトを含むすべてのタイプの変数です!)。

'..... onkeyup="showResult(this.value,'+JSON.stringify(l)+');" .....'
于 2012-06-08T19:29:17.723 に答える