我如何在jQuery中重复一个函数?

时间:2013-01-06 23:37:12

标签: javascript html jquery

我尝试在此函数中使用无限循环,但是当我设置setInterval时,该函数不会重复。问题是用户发送表单并在时间间隔过后。该函数保留在已发送的消息上,并且不从头开始。请参阅我的JSBin

使用Javascript:

$(function(){

  function show_fb() {
    $("#feedback_box").show("slow");    
  }

  function hideAll() {
    $("#feedback_box").hide("slow");
  }

  $("#feedback_box #close").click(function() { // When the X is pressed
    $("#feedback_box").hide("slow"); // Hide the form
  });

  setInterval(show_fb,1000); // Show the form after 6 seconds , you can change 6000 to anything you like    

  $("#feedback_form").submit(function() { //When the form is submitted

    $('#feedback_form #fb_title').css('background-color','#4444FF').text('Sending...').slideDown(900); //show "Sending" message

    $.post("form_submit.php",{ mesaj:$('#mesaj').val(),rand:Math.random() } ,function(data) { //subimit the feedback via AJAX

        $('#feed_subm').attr("disabled", "false"); //disable the "SEND" button
        $('#feedback_form #fb_title').css('background-color','#C33').text('Thank You!').slideDown(900); //Shows a thank you message
        setTimeout(hideAll,2000); // Hide the form after 2 seconds

    });

  });

  return false; //Tells the code not to post the form physically

});

HTML:

</head>
<body>

    <div id="feedback_box"> 
        <form id="feedback_form"> 
            <span id="fb_title">Give us some feedback :)</span><span id="close">X</span> 
            <textarea id="mesaj"></textarea> 
            <input type="submit" value="Send" class="mysubm" id="feed_subm"/> 
        </form> 
    </div>

</body>

1 个答案:

答案 0 :(得分:0)

你可以像这样在jQuery中重复一个函数:

<强>使用Javascript:

$(document).ready(function() {

  // First we will create the function that will be repeated
  function repeat() {

    setTimeout(function() {

      // Enter your code that you want to repeat in here

      repeat(); // This is where the function repeats

    }, 1); // Where 1 is the delay (in milliseconds)

  }

  repeat(); // Here we are initially firing the function

});

在上面的示例中,我无法理解为什么你需要不断重复的函数,但你的问题是如何在jQuery中重复一个函数?

我认为这意味着如何在jQuery中重复一个函数?

嗯,这是你的答案。