简体   繁体   中英

jQuery onclick Event call a function

I have the following code:

 function hvcm_wait() { waitingDialog.show('Please wait while your VM is rebooting...'); } $('#hv_ConfirmShutDown').on('show.bs.modal', function(e) { $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="btn btn-danger btn-ok">Shutdown Now</a> 

How do I call the javascript function hvcm_wait() when .btn-ok is clicked is clicked in Modal?

Any help would be highly apperciated. Thanks!

Assuming that .btn-ok is not present when script is loaded, so use event-delegation.

Add these lines after hvcm_wait() function

$('#hv_ConfirmShutDown').on('click', '.btn-ok', function() {
    hvcm_wait();
})

Or if it is present in DOM then you can directly do this

$('.btn-ok').click(function() {
    hvcm_wait();
})

或者您可以将其直接添加到HTML中,如下所示:

<a class="btn btn-danger btn-ok" onclick="hvcm_wait()">Shutdown Now</a>

I would use this, first in the $() you search for the class btn-ok, then you hand it a onClick handler that executes the function.

$(".btn-ok").click(function(){
    hvcm_wait();
});

You are adding href attribute here. First you need to prevent the href and call the normal function.

 $(".btn-ok").click(function(event){
     event.preventDefault();
     hvcm_wait(); 
 });

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