简体   繁体   中英

How do I insert a button in Javascript that can reach a function with onclick()?

I have a javascript file that checks the server for results. If it fails to get the results after a certain number of attempts, I want to add a button to the page so the user can manually check for results. However, the button did not work when added. How do I fix it, do I need to do something to get the function in the scope of the button?

This is the code that adds the button:

$('.submitter').after("<span class='btn' onClick=delayDoing(0)>Check again</span>")

Which created the following button that does nothing:

<span class="btn" onclick="delayDoing(0)">Check again</span>

Below is the file of javascript. (I shortened it and removed some of the ERB stuff.)

 function delayDoing(attempts){
     setTimeout(function(){checkServer(attempts)}, 3000);
 }

 function checkServer(attempts){
     if ($('.results').css('opacity') === '0') { //no results           
         if(attempts < 4) {   
             // {code to check for results...}

             delayDoing(attempts+1);
         }
         else{
             $('.submitter').after("<span class='btn' onClick='delayDoing(0)'>Check again</span>")
         }
     }
}

jQuery(function() {
    delayDoing(0)
});

I would do something like this:

var submit = $('.submitter'); //reference to the submitter button
var newButton = $("<span class='btn'>Check again</span>"); //in-memory button

submit.after( newButton ); //append the button to the DOM
newButton.click(function(){ delayDoing(0); }); //add a click event to the button and call for your function

Remember that javascript is compiled as it's loaded in the browser, since the element didn't exist on compile-time it won't trigger the click event, what you need to do is to append the element to the DOM AND add an event.

Hope this helps, cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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