简体   繁体   中英

how to use window.onload=function with multiple jQuery click events

I have two different buttons in the navigation menu, they are anchor links to a tab switcher on the home page, which has two tabs. I need the navigation buttons to change the active tab, when clicked. It should be a simple code, but I am a newbie in JS.

I need this to call the functions after the page loads, this way, it will work from other pages too, not just from the home page.

The first function works in itself as it should. The function also works when the button is clicked on a different page. It calls the homepage, then changes the active tab after page load:

add_action( 'wp_footer', function () { ?>
<script>

jQuery('#menu-item-15507 a').on('click', window.onload=function myfunction_1() {
    jQuery( '#one-to-one a' ).click();
    return true;
});

</script>
<?php } );

But when I add the second event and function, the tabs are not changing on pageload. It works on the same page (home page), but not when fired from a different page:

add_action( 'wp_footer', function () { ?>
<script>

jQuery('#menu-item-15507 a').on('click', window.onload=function myfunction_1() {
    jQuery( '#one-to-one a' ).click();
    return true;
});

jQuery('#menu-item-16848 a').on('click', window.onload=function myfunction_2() {
    jQuery( '#courses a' ).click();
    return true;
});

</script>
<?php } );

How am I supposed to change the code to get both functions to work on page load as well?

One problem is - don't invoke the on- setters if you need to run more than one function - use addEventListener instead.

But assigning to .onload inside a click listener doesn't make any sense anyway - by the time the user can click, the window will likely have loaded anyway.

The standard way to run something when the page is ready in jQuery is to use the main $ function's callback.

$(() => {
  const clickOne = () => $('#one-to-one a').click();
  clickOne();
  $('#menu-item-15507 a').on('click', clickOne);

  const clickCourses = () => $('#one-to-one a').click();
  clickCourses();
  $('#courses a').on('click', clickCourses);
});

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