简体   繁体   English

使用jQuery从另一个页面加载随机元素

[英]Loading a random element from another page using jquery

I have a page (myPage.aspx) that contains a number of divs. 我有一个页面(myPage.aspx),其中包含许多div。 EG. 例如。

    <div class="quote">something 1</div>
    <div class="quote">something 2</div>
    <div class="quote">something 3</div>
    <div class="quote">something 4</div>
    <div class="quote">something 5</div>

Using jquery's ajax function, from other pages I would like to: 从其他页面使用jquery的ajax函数,我想:

a) Test how many .quote divs on on the page myPage.aspx a)测试页面myPage.aspx上有多少个.quote div

b) Load a random .quote div from myPage.aspx into a specific id div (#myDiv), on my current page. b)将myPage.aspx中的随机.quote div加载到当前页面上的特定ID div(#myDiv)中。

Would really appreciate any help offers. 非常感谢任何帮助。

You can use something like this: 您可以使用如下形式:

$.get('/path/to/myPage.aspx', function(data)
{
    var $quotes = $(data).find('div.quote'),
        count = $quotes.length,
        $random = $quotes.eq( Math.floor(Math.random() * count) );

    $('#myDiv').append( $random );
});

See it here in action: http://jsfiddle.net/j2AGL/ 实际操作见这里: http : //jsfiddle.net/j2AGL/

You can use jQuery ajax() method to get the content from myPage.aspx and the traverse through its content using jQuery apis. 您可以使用jQuery ajax()方法从myPage.aspx获取内容,并使用jQuery myPage.aspx遍历其内容。 Try this. 尝试这个。

$.ajax({
   url: "myPage.aspx",
   success: function(data){
       var $data = $(data);  
       var $quotes = $data.find('div.quote');

       //$quotes.length will give you the number of quote divs in myPage.aspx

       var randomQuote = Math.floor(Math.random() * $quotes.length));
       $('#myDiv').append($quotes.eq(randomQuote));
   }
});

You could use a callback function to achieve this. 您可以使用回调函数来实现此目的。 For example: 例如:

This is what should appear on your myPage.aspx: 这应该出现在myPage.aspx上:

<div id="result">
    <div class="quote">something 1</div>
    <div class="quote">something 2</div>
    <div class="quote">something 3</div>
    <div class="quote">something 4</div>
    <div class="quote">something 5</div>
</div>

This would be your ajax function: 这将是您的ajax函数:

<script>
$.ajax({
url: '/myPage.aspx',
type: 'get',
success: function(data) {
    var myLen=$(data).children().size(); 
    var myNum=Math.floor(Math.random()*(myLen-1)); 
    var myData=$(data).children().eq(myNum).text(); 
    $("div#myDiv").text(myData);
    }
});
</script>

This function basically: 1. Retrieves all the HTML on your 2nd page 2. Gets the number of that contain a quote 3. Gets a random number between 0 and 1 less than the # of quotes since array's start at 0 in JavaScript 4. Gets the text from the quote with that random number 5. Insert the quote into the #myDiv element. 此函数的基本功能是: 1.检索第二页上的所有HTML 2.获取包含引号的数字。3.从JavaScript数组的起始位置为0开始,获取小于引号#的0到1之间的随机数。带有该随机数的引号中的文本。5.将引号插入#myDiv元素中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM