简体   繁体   中英

Onclick event won't trigger url direct

I have a working snippet that I want to tweak. I am trying to change the OnClick event (see altered code), but I can't get the OnClick event to trigger.

What works:

add_action( 'woocommerce_before_single_product', 'my_button_function', 10 );
function my_button_function() {
  global $product;
  echo ' <button type="button" class="back-button" onclick="history.back();"> Back to overview </button> '; 
}

Altered code (I don't get any errors but the button just doesn't do anything)

add_action( 'woocommerce_before_single_product', 'my_button_function', 10 );
function my_button_function() {
        global $product;
        echo '<button type="button" class="back-button" onclick="window.open("https://www.lanacreations.nl/products");"> Back to overview </button>'; 
    }

I also tried to put the onclick event into a seperate function:

function myClickFunction() {
  window.open("https://www.lanacreations.nl/products");
}

add_action( 'woocommerce_before_single_product', 'my_button_function', 10 );
function my_button_function() {
    global $product;
    echo ' <button type="button" class="back-button" onclick="myClickFunction()"> Back to overview </button> '; 

Does anyone see what I am doing wrong?

Thank you!

Your last block of code is invalid, it's conflating PHP and JavaScript. Your second block of would work, but it appears you just have a syntax error. You've got double quotes inside your attribute that's encapsulated with double quotes - so your HTML is breaking, and is actually being interpreted as:

onclick="window.open(" https:="" www.lanacreations.nl="" products");"="">

So to fix that, you can replace the double quotes inside your JavaScript function with single quotes, provided that you Escape them. If you start a string with ' , you can "escape" a single quote with a forward slash \\' to tell PHP "I want you to actually PUT a single quote here, NOT treat this like the end of the string".

Try this:

add_action( 'woocommerce_before_single_product', 'my_button_function', 10 );
function my_button_function() {
    global $product;
    echo '<button type="button" class="back-button" onclick="window.open(\'https://www.lanacreations.nl/products\');"> Back to overview </button>'; 
}

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