2010-11-15 56 views
0

在wordpress中,我有一個頁面設置爲使用jQuery隨機發布,我期待將這個(隨機)頁面的各個部分拉到當前的各個部分(家)此刻頁面的代碼如下:jQuery將各種id加載到頁面的各個部分

$('#wrongQuote').load('random/index.php #wrongSaying' + '?noCache=' + Math.floor(Math.random()*10001)); 
$('#sayingBy').load('random/index.php #author' + '?noCache=' + Math.floor(Math.random()*10001)); 
$('#actualQuote').load('random/index.php #actualSaying' + '?noCache=' + Math.floor(Math.random()*10001));

麻煩的是,這是在隨機#wrongSaying,#author和#actualSaying拉......我需要的是得到隨機的,但匹配# wrongSaying/#author/#actualSaying

所以我想我需要的是'random/index.php #wrongSaying'然後把div#x插入div#a,div#f到div#e和如此...

任何想法/幫助將不勝感激!

安迪

+0

你的代碼實際上並沒有發送'noCache'值; *#wrongSaying'(或其他ID)應該*在查詢字符串之後*。 – PleaseStand 2010-11-15 22:23:10

+0

@idealmachine - 在頁面上沒有多個id,所有的好處在於id/classes之間的區別等等 - 感謝noCache上的點我會檢查/修改 – tbwcf 2010-11-15 22:26:39

+0

查詢字符串應該是一個單獨的參數,而不是連接到網址。 – 2010-11-15 22:43:45

回答

7

我不會用.load()在這裏3級的要求,我會做自己加載並使用一個請求到服務器$.get(),這樣做:

$.get('random/index.php', { noCache: Math.floor(Math.random()*10001) }, 
    function(data) { 
    data = $(data); 
    $('#wrongQuote').html(data.find('#wrongSaying')); 
    $('#sayingBy').html(data.find('#author')); 
    $('#actualQuote').html(data.find('#actualSaying')); 
}); 

片段加載你得到.load()是你自己做不到的東西......當你重複同樣的請求時,它是你不應該做你自己...有效率,並提出一個請求,更具可讀性的代碼IMO。

+0

完美,作品一種享受,非常感謝! – tbwcf 2010-11-16 09:25:02

0

你可以把它全部加載到一個隱藏的元素,並拉出隱藏元素:

$(hiddenElement).load('random/index.php?noCache=' + Math.floor(Math.random()*10001)); 

$(elementYouWanToSet).html($(hiddenElement).find(elementYouWant)); 
+0

謝謝我有一個類似的想法,但不知道它的最佳方法?我猜有時髒工作.. – tbwcf 2010-11-15 22:29:27

+0

修改服務器端代碼將是乾淨的方式,但除非隨機/ index.php是一個巨大的文件,骯髒的方式應該完成工作。 – generalhenry 2010-11-15 22:31:23

+0

只要您傳遞'.load()'正確的ID,就可以將它加載到正確的元素中(沒有隱藏的元素)。 – 2010-11-15 22:52:24

0

.load()需要3個參數,一個URL,查詢數據,以及一個回調函數。

嘗試改變你的線把這些:

var randomID = Math.floor(Math.random()*10001); 
$('#wrongQuote').load('random/index.php #wrongSaying', 'noCache='+randomID); 
$('#sayingBy').load('random/index.php #author', 'noCache='+randomID); 
$('#actualQuote').load('random/index.php #actualSaying', 'noCache='+randomID); 

這不會有重複的ID,因爲只有給​​ID被插入到DOM,其餘的被丟棄的任何問題。

+0

謝謝,這使整個無緩存位整齊,但仍然有三次觸擊頁面的問題,所以得到三個隨機部分的說法,不匹配。 – tbwcf 2010-11-16 09:30:04