0

たとえば、URLからパラメーターを取得しようとしています。

www.x.com/?source=display&zone=lc&topic=クラウド

したがって、トピックが「クラウド」の場合は、3 つの個別の div を並べ替えたいと思います。

これは、これまでのヘッダーにあるものです。

<script type="text/javascript">
if (window.location.search.indexOf('topic=cloud') > -1) {
    alert('track present');
    $(".one").insertAfter(".two");
} else {
    $(".two").insertAfter(".three");
    alert('track not here');
}
</script>

html は次のようになります。

<div class="one">seo</div>
<div class="two">cloud</div>
<div class="three">social</div>

アラートが表示されますが、使用すると.insertAfter();

私は何も得ません

4

3 に答える 3

2

PHP も使用できる場合 (タグによると、使用できる場合)、PHP でこれを行うことをお勧めします。そのため、クライアント側の操作は必要ありません。基本的:

<?php if (isset($_GET['topic']) && 'cloud' == $_GET['topic']) { ?>
    <div class="one"></div>
    <div class="two">cloud</div>
    <div class="three">social</div>
<?php } else { ?>
    <div class="one">seo</div>        
    <div class="three">social</div>
    <div class="two">cloud</div>
<?php } ?>
于 2013-02-26T22:08:17.677 に答える
2

document ready を使用すると、コードは期待どおりに動作します。

<script type="text/javascript">
$(function() { //<-- you are missing this

if (window.location.search.indexOf('topic=cloud') > -1) {
    alert('track present');
    $(".one").insertAfter(".two");
} else {
    $(".two").insertAfter(".three");
    alert('track not here');
}

}); // <-- and the closing element
</script>

以下は問題なく動作します。試してみて、コードと比較してみてください (Juan Mendes が何が起こっているのかを説明しているので、Juan Mendes のコメントも読んでください)。

<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script>
    $(function() {  
        if (window.location.search.indexOf('topic=cloud') > -1) {
            alert('track present');
            $(".one").insertAfter(".two");
        } else {
            $(".two").insertAfter(".three");
            alert('track not here');
        }    
    });
  </script>
</head>
<body>
  <div class="one">seo</div>
  <div class="two">cloud</div>
  <div class="three">social</div>
</body>
</html>
于 2013-02-26T22:08:29.147 に答える
0

$おそらく、jQueryがまだ定義されていないことに関連するエラーが発生しています。FireBug または Web 開発者ツールを調べて確認してください。その行までは jQuery を参照していない$ため、エラーはスローされません。

可能性 1:ページに jQuery が含まれていることを確認します。

ローカルの場合は次のようになります。

<script type="text/javascript" src="js/jquery.js"></script>

CDN (ホスト) バージョンを使用している場合は、次のようになります。

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

可能性 2:参照する前に jQuery が含まれていることを確認してください$<script>インクルードをスクリプトの残りの上に移動します。

可能性 3: Prototype のような別のライブラリを使用している場合は、jQuery(の代わりに$)直接参照します。

<script type="text/javascript">
if (window.location.search.indexOf('topic=cloud') > -1) {
    alert('track present');
    jQuery(".one").insertAfter(".two"); // note jQuery, not $
} else {
    jQuery(".two").insertAfter(".three"); // note jQuery, not $
    alert('track not here');
}
</script>
于 2013-02-26T22:06:31.873 に答える