开发者

Random selection in jQuery

Im using the following function to hide a series of forms on a page:

$('.ask').toggle(function() {
      $(this).text('-').next('.addtitle').slideDown('fast');
    }, function() {
      $(this).text('+').next('.addtitle').slideUp('fast');
});

There can be anything from 0 to 5 forms on the开发者_开发技巧 page all with the class .ask

What I want to be able to do is to select one form NOT to hide, so the jQuery needs to hide all put one of the forms on the page randomly.

How can I achieve this?


You can just hide one initially at random, like this:

$('.ask').toggle(function() {
  $(this).text('-').next('.addtitle').slideDown('fast');
}, function() {
  $(this).text('+').next('.addtitle').slideUp('fast');
});
var articles = $('.addtitle');
articles .hide().eq(Math.random() * articles.length).prev('.ask').click();​​​​​​​​

This is based on your previous question's markup, you can view a quick demo here :)


You could use the .not() function to exclude some element at a given random index:

var indexToExclude = Math.floor(Math.random() * $('.ask').length);
$('.ask').not(':eq(' + indexToExclude + ')').toggle(function() {
    $(this).text('-').next('.addtitle').slideDown('fast');
}, function() {
    $(this).text('+').next('.addtitle').slideUp('fast');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜