简体   繁体   中英

How To Call A Javascript Function From Inside Jquery When An ID is Clicked

Let's say I have a javascript function called capturedata(); I need to call this function when this button is clicked

<button id='yes'></button> 

For some reasons, I do not want to use any event handler on the html like onclick='capturedata()' Now I have use Jquery this way

$(document).ready(function(){
  $("#yes").click();
  capturedata();
});

But this is not working. I need a better way to handle this, and I do not want to use any event handler like onclick on the html. I want the action to happen automatically once the button is clicked.

Almost but not quite, you'll need to register capturedata as the callback for the click event.

$(document).ready(function(){
    $("#yes").click(capturedata);
});

Your click method requires a callback function as its first argument

eg .click(() => {})

see DOCS

Note how calling .click() will invoke a click event and not listen for one.

Suggestion : use addEventListener('click', {yourCallback}) see DOCS

$(document).ready(function(){
  $("#yes").click(function(){
    capturedata();
    // some code
  });
});

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