简体   繁体   中英

Javascript in functions.php

I cant seem to get the following code to work;

function add_js_functions(){

$gpls_woo_rfq_cart = 
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');

if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);    
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");

if(1 != 0) {
    getQuoteIcon[0].style.display = "none";
   }

</script>
<?php }
add_action('init','add_js_functions');

The php above the script stores a variable from the quote form on the number of items in the form.

I tried the javascript by itself and its seemed to work but its not working in the functions file.

At the moment im using (1,= 0) to make sure its true and to hide the item so I know the JS works; what will happen afterwards is this will become;

if (<?php $count != 0 ?>) {
//rest of the JS here
} 

So that when the page loads, if the form is empty of items then this icon will be hidden (it starts off as inline-block and i dont know how to change this).

I think you want your php to be <?php echo $count?= 0 ?> .

Your PHP is executed server-side, and Javascript client side, the two don't communicate by passing variables between the two. In order to get your PHP variable into your Javascript, you need to echo it.

It looks like you are loading the JS too soon and the element you are targeting isn't available yet.

Use add_action('wp_footer') to load the JS in the footer.

function add_js_functions(){

$gpls_woo_rfq_cart = 
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');

if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);    
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");

if(1 != 0) {
    getQuoteIcon[0].style.display = "none";
   }

</script>
<?php }
add_action('wp_footer','add_js_functions');

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