JQuery: Click a random link on document ready
I have five links on a page which dis开发者_运维知识库play different content on another part of the page when clicked. Each link has an ID and I have a simple click function on document ready to select the first link:
$('#link1').click();
How can I have it click one of the five links at random on document ready, instead of #link1 specifically? And yes, I realize that a click function probably isn't the ideal way to handle this.
Thanks in advance!
The smoov jQuery way of doing things:
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
random: function(a, i, m, r) {
if (i == 0) {
jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
};
return i == jQuery.jQueryRandom;
} });
<script type="text/javascript">
$().ready(function() {
alert($("a:random").click());
});
</script>
(I knew about custom selectors, but still shamelessly stolen from here)
Slightly less smoov:
$(function() {
var links = $('a');
var randomNum = Math.floor(Math.random()*links.length)
links.get(randomNumber).click();
}
If you want links with an ID that start with link, you can always do:
var links = $("a[id^='link']");
And now it doesn't matter whether you use numbers or whatever. Anything that has an ID that starts with link. (naturally, you could apply it to a particular css class too)
something like this?
var randomnumber=Math.floor(Math.random()*5)
$($('a').get(randomnumber)).click();
Assuming the links of interest start with 'link' followed by a number:
$('a[id="link' + Math.floor(Math.random() * 5) + '"]')[0].click();
I think it would be
links = new Array();
$('a').each(function() { links.push($(this)) });
el = links[Math.floor(Math.random()*links.length)]
el.click();
That grabs all the links on the page and puts them into an array and then clicks on one of them.
Another possible hack:
$('a[href^="link"]').sort(function(){return Math.random()-0.5}).eq(0).click()
The above code will shuffle the links, and return the first one. Then you can trigger 'click' of the returned element
精彩评论