开发者

Can you load a random file each time you click the same button with jQuery?

I have 4 contact forms we would like to rotate for testing. I don't want to run these in separate campaigns and for such a simple thing its overkill. Is it possible to have a group of s开发者_Python百科ay 4 forms and load them randomly ( a different form ) each time you click a button?

$(function() {
    $("a.random")click.(function){
    //?
    });
});


Yes.

<form id="form0" class="test_form">
<form id="form1" class="test_form" style="display: none;">
<form id="form2" class="test_form" style="display: none;">
<form id="form3" class="test_form" style="display: none;">

$(function() {
    $("a.random")click.(function){
       $(".test_form").hide();
       var formNumber = Math.floor(Math.random() * 4);//will equal a number between 0 and 3
       $("#form" + formNumber).show();
    });
});


var n = Math.floor( Math.random() * 4 ) + 1;

This will give you a random integer number between 1 and 4. Based on that, you run different commands.


You can have the forms like this:

<div id="forms">
  <form style="display:none;" ...>
    ...
  </form>
  <form style="display:none;" ...><!-- the second form -->
    ...
  </form>
  ...
</div>
<a href="#" id="randomForm">Show random form</a>

And then in your jQuery:

$('#randomForm').click(function() {
    var forms = $('#forms > form');
    forms.hide();
    forms.eq(Math.floor(Math.random() * forms.length)).show();
});

Look at it working here.


This is verbose but something like this should work:

$(function() {
    $("a.random")click.(function){
        var randomnumber=Math.floor(Math.random()*5)
        switch (randomnumber) {
          case 1:
           $(this).attr("href",[url 1]);
           break;
          case 2:
           $(this).attr("href",[url 2]);
           break;
          case 3:
           $(this).attr("href",[url 3]);
           break;
          default:
           $(this).attr("href",[url 4]);
           break;
        }
    });
});


Can we use a pure javascript and dom here, see if it works for you.

var arr = [form1, form2, form3, form4];

var fn = function(arr){
  var cur_frm = arr[Math.floor(Math.random() * arr.length)];
  cur_frm.style.display = 'block';

  for(i=0; i<arr.length;i++){
    if(arr[i] != cur_frm) arr[i].style.display = 'none';
  }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜