开发者

jQuery load various id's into sections of the page

开发者 https://www.devze.com 2023-01-25 00:53 出处:网络
In wordpress I have a page set up to pull in a random post, using jQuery I\'m looking to pull in sections of this (random) page to various sections on the current (home) page at the moment the code is

In wordpress I have a page set up to pull in a random post, using jQuery I'm looking to pull in sections of this (random) page to various sections on the current (home) page at the moment the code is as below:

$('#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));

The trouble is this is pulling in a random #wrongSaying, #author and #actualSaying... what I need is to get random, but matching #wrongSaying / #author / #actualSaying

So I guess what I need is get this page 'random/index.php #wrongSaying' then take div#x and insert into div#a, div#f into div#e and so on...

Any ideas / help would be much appreciated!

Andy


I wouldn't use .load() with 3 requests here, I'd do the loading yourself and make one request to the server using $.get(), like this:

$.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'));
});

The fragment loading you get with .load() is nothing you can't do yourself...and when you're repeating the same request it's something you shouldn't do yourself...be efficient and make one request, with more readable code IMO.


.load() takes 3 parameters, a url, query data, and a callback function.

Try to change your lines to these:

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

This does not have any problem with duplicate IDs because only the ID given to .load() is inserted into the DOM, the rest is discarded.


You can load it all into a hidden element and pull out of the hidden element:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号