0

更新:応答してくれてありがとう。document.write() が廃止されたことに気づきませんでした。学習の列にもう 1 つのノッチを追加します。ここに投稿されたアドバイスを受け入れますが、元の質問のコンテキストで回答が意味をなすように、元の質問はそのままにしておきます。


私はいくつかのかなり長い write() 引数をコーディングしている最中であり、構文、読みやすさ、およびパフォーマンスを考慮して、次の例のどれに従うのが最善かを決定しようとしています. するべきか

を。それらをすべて 1 行にまとめます。

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" + someVariable + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" + someVariable);

</script>

b. 読みやすくするために、改行を追加して分割します。

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    document.write("<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>" 
        + someVariable
        + "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>" 
        + someVariable);

</script>

c. 複数の変数を使用してそれらを分割します。

<script>

    var someVariable = "(<a href=\"http://www.example.com\">Link<\/a>)";

    var partOne = "<p>Supergroovalisticprosifunkstication and Supercalifragilisticexpialidocious are very long words.</p>"; 
    var partTwo = "<p>Dociousaliexpisticfragilicalirepus is Supercalifragilisticexpialidocious spelled backwards.</p>"; 

    document.write(partOne + someVariable + partTwo + someVariable);

</script>

前もって感謝します。

4

3 に答える 3

3

私の腸の反応は次のとおりです。(あなたの例は貧弱です。ビヘイビアーレイヤーにコンテンツの大きな塊を書くべきではありません。)

これを行う必要があるときはいつでも、次のいずれかを連結します。

var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' +
    ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' +
    'qersdfasdfasdfasdfasdf';
document.write(longVar);

または、非常に長くなる場合は、配列を結合することでパフォーマンスが向上する可能性があります。

var longVar = [
    'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf',
    ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ',
    'qersdfasdfasdfasdfasdf'
].join('');
document.write(longVar);
于 2008-10-27T02:40:31.843 に答える
0

私はそれを書きますが、読みやすく、維持するのが最も簡単になるでしょう。次に、パフォーマンスをテストします。遅すぎる場合は、許容できる速度になるまでアルゴリズムを段階的に改善してみてください。

パフォーマンスを改善するためのアイデア: - スクリプトが縮小されていることを確認します。- サーバー上でできるだけ多くの前処理を行い、「処理された」スクリプトを提供します。

最小化ツール (jsMin など) を使用すると、読みやすくするために空白や改行を入れることで問題が発生することはありません。

于 2008-10-27T02:45:49.367 に答える
0

-- and it is a bad example to use document.write() as it belongs to the 90ties and was deprecated with the introduction of HTML4 in 1998 ...

サーバー側で何かを取得した場合は、そこでコード生成を処理することをお勧めします...

文字列の連結の問題については、まぶたのないことに同意します!-)

編集 (29/10)

コメントへのコメントとして (コード表記が必要です)

<script type="text/javascript">
  window.onload = function(){
    var newD = document.createElement("div");
    newD.appendChild(document.createTextNode("Hello World"));
    document.getElementsByTagName("body")[0].appendChild(newD);
  }
</script>

このようにして、ドキュメントに何かが挿入されます...

于 2008-10-27T03:42:27.740 に答える