![](/img/trans.png)
[英]Styling the payment methods in the WooCommerce checkout page (Custom Javascript required)
[英]Javascript executing but not keeping value on Woocommerce checkout page
我在 functions.php 中使用它在 Woocommerce 結帳頁面上執行。
我看到顯示:沒有被應用,但只有幾毫秒。
知道如何在元素上保持樣式嗎?
// add script to checkout page
add_action( 'wp_footer', 'add_javascript_function', 9999 );
function add_javascript_function() {
global $wp;
if ( is_checkout() && empty( $wp->query_vars['order-pay'] ) && ! isset( $wp->query_vars['order-received'] ) ) {
echo '<script>
window.addEventListener("DOMContentLoaded", () => {
let myDivs = document.getElementsByClassName("products");
for(let i = 2; i < myDivs.length; i++) {
myDivs[i].style.display="none"; }
});
</script>';
}
}
還想添加一個按鈕來切換這個 function 隱藏的項目。但這個問題讓我發瘋。
提前致謝。
使用 JS 設置您的 HTML 元素的初始可見性將不起作用,因為在您的 function 運行后update_checkout
被觸發,這會刷新結帳的訂單審查部分。 這就是為什么您看到您的 styles 僅被短暫應用的原因。
您應該使用 CSS 設置產品的可見性,然后在單擊按鈕時使用 JS 否決那些 styles,在隱藏和可見之間切換。
woocommerce_review_order_after_cart_contents
掛鈎為您提供了一個為此添加按鈕的好地方。 您還可以在那里添加您的 CSS 和 JS,這樣所有內容都包含在一個整潔的小 function 中。像這樣:
add_action ('woocommerce_review_order_after_cart_contents', function() {
?>
<style>
.woocommerce-checkout-review-order-table .cart_item:nth-child(n+3) {
display: none;
}
</style>
<script>
jQuery( function( $ ) {
$( '#product-toggle' ).on( 'click', 'span.button', function() {
if ( $( this ).data( 'show' ) === true ) {
$( '.woocommerce-checkout-review-order-table .cart_item').show();
$( this ).text( 'Show less products' ).data( 'show', false );
} else {
$( '.woocommerce-checkout-review-order-table .cart_item').slice(2).hide();
$( this ).text( 'Show all products' ).data( 'show', true );
}
} );
} );
</script>
<?php
echo '<tr id="product-toggle"><td colspan="2"><span class="button" data-show="true">Show all products</span></td></tr>';
}, 10 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.