2013-02-26 34 views
0

我試圖從例如一個url抓取參數。jquery從url獲得價值,然後重新命令div

www.x.com/?source=display &區= LC &話題=雲

所以,如果題目是「雲」,它是那麼我想重新爲了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();

我什麼也得不到

回答

0

也許你會得到一個與jQuery的相關的錯誤尚未定義。查看FireBug或Web Developer工具來檢查。直到那一行,你還沒有引用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:如果您使用的是像原型的另一個庫,參考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> 
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 } ?> 
+1

這似乎比最初插入錯誤的順序更好,更好地做到這一點正確的f第一次比稍後修復它 – 2013-02-26 22:09:29

+0

同意。爲什麼要傳遞給客戶端可以在服務器上完成什麼?較老/較慢/ JS禁用的瀏覽器會喜歡它來自服務器。 – 2013-02-26 22:21:20

2

使用文檔準備就緒,你的代碼會做你所期望的:

<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> 

下工作正常,試試吧,看看它是如何比較你的代碼(也看過娟門德斯評論,因爲他解釋了發生的事情):

<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> 
+1

解釋:OP的代碼試圖在解析HTML之前運行,因此''('。one')'和'$('。two')'在那時不存在。這是我不喜歡jQuery的原因之一,在空集合上調用方法時沒有錯誤隱藏了很多錯誤 – 2013-02-26 22:11:57

+0

我已更新到此。而且我還沒有重新排列我的div,我可以忘記的任何東西? – user388069 2013-02-26 22:15:20

+1

似乎在這裏工作:http://jsfiddle.net/xUVLT/ – insertusernamehere 2013-02-26 22:18:54