简体   繁体   English

我正在尝试制作一个显示/隐藏样式按钮以在 woocommerce 产品描述中显示一段文本

[英]I'm trying to make a show/hide style button to display in woocommerce product description for a chunk of text

So I am fairly new to coding in general and I am currently working on an eCommerce website to develop my skills.因此,总的来说,我对编码还很陌生,我目前正在电子商务网站上工作以发展我的技能。

Using woocommerce in WordPress, I am trying to add a 'show/hide' style button to display or hide a chunk of text using JS, but not sure where I'm going wrong.在 WordPress 中使用 woocommerce,我正在尝试添加一个“显示/隐藏”样式按钮来使用 JS 显示或隐藏一段文本,但不确定我哪里出错了。 Here is my JS code which is situated in my functions.php file:这是我的 JS 代码,它位于我的 functions.php 文件中:

var i=0;
function read(){
    if(!i){
        document.getElementByID("batbut").style.display ="inline";
        document.getElementByID("read").innerHTML="Close";
        i=1;
    }
    else{
        document.getElementByID("batbut").style.display ="none";
        document.getElementByID("read").innerHTML="Battery Warning Info";
        i=0;
    }
}

"batbut" is the span id for the chunk of text "read" is the button id "read()" is the onclick attribute “batbut”是文本块的 span id “read”是按钮 id “read()”是 onclick 属性

the chunk of text is currently hidden using css:当前使用 css 隐藏文本块:

#batbut {
    display: none;
}

any help would be much appreciated and if any more information is required just lmk.任何帮助将不胜感激,如果需要更多信息,只需 lmk。 Thanks!谢谢!

Try something like this,试试这样的,

check if your DOM nodes exists if yes the toggle based on the current display state of the batbut element检查您的 DOM 节点是否存在,如果是,则切换基于 batbut 元素的当前显示 state

function read() {
  const elmBatbut = document.getElementById("batbut");
  const elmRead = document.getElementById("read");

  if (!elmBatbut || !elmRead) return;

  if (elmBatbut.style.display === 'none') {
    elmBatbut.style.display = "inline";
    elmRead.innerHTML = "Close";
  } else {
    elmBatbut.style.display = "none";
    elmRead.innerHTML = "Battery Warning Info";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM