如何使用Java脚本中的一个功能使多个按钮独立工作?

时间:2019-07-12 13:01:10

标签: javascript html button show-hide

如何制作更多这些按钮,使它们可以独立工作?我知道所有这些都与id有关,但是如何使用一个具有多个id的函数呢?

function showme(id) {
  var divid = document.getElementById(id);
  var clicky = document.getElementById("clicky");
  if (divid.style.display == 'block') {
    divid.style.display = 'none';
    clicky.innerHTML = 'MORE <i class="fa fa-arrow-down"></i>';
  } else {
    divid.style.display = 'block';
    clicky.innerHTML = 'LESS <i class="fa fa-arrow-up"></i>';
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<i>Click on more. I want to have two buttons, which work independently.</i><br>

<div class="tp-caption rev-btn rev-hiddenicon  rs-hover-ready rev-mre-btn" onclick="showme('widget');" href="javascript:;" id="clicky">MORE 
  <i class="fa fa-arrow-down"></i>
</div>

<div id="widget" style="display:none;">
  TEXT 1
</div>

1 个答案:

答案 0 :(得分:0)

首先,我将删除您在HTML中添加的onclick侦听器,这不是一个好习惯。我将其添加到JS上,选择要添加点击侦听器的所有按钮/ div,然后将其附加。

为此,您可以使用.getElementsByClassName()(也可以使用querySelectorAll())选择所有元素,并将元素保存在变量中,然后循环所有元素并附加onclick函数。

函数上下文(this)将是被单击的按钮/ div,要知道,在函数内部您可以找到图标和包含的div(我将div移入了里面是因为它使查找起来更加容易,并且知道应切换哪个div)。在拥有内部div和图标之后,现在就可以由您来管理div的打开/关闭以及图标转换...

看看下面的代码以了解主要思想。

var buttons = document.getElementsByClassName("button-open-container");
for (var i = 0; i < buttons.length; i++){
  buttons[i].onclick = showme;
}

function showme(ev) {   
  var spanText = this.querySelector(".my-text");
  var childDiv = this.querySelector(".my-container");  
  var icon = this.querySelector(".my-icon");  
  
  if (childDiv.style.display == "none"){
    childDiv.style.display = "block";
    icon.className = "my-icon fa fa-arrow-up";
    spanText.innerText = "LESS"
  }
  else{
    childDiv.style.display = "none";
    icon.className = "my-icon fa fa-arrow-down";
    spanText.innerText = "MORE";
  }    
}
.button-open-container{
  display: inline-block;
  margin: 8px;  
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<i>Click on more. I want to have two buttons, which work independently.</i><br>

<div class="tp-caption rev-btn rev-hiddenicon rs-hover-ready rev-mre-btn button-open-container">
  <span class='my-text'>MORE</span>
  <i class="my-icon fa fa-arrow-down"></i>
  <div class='my-container' style="display:none;">
    TEXT 1
  </div>
</div>

<div class="tp-caption rev-btn rev-hiddenicon rs-hover-ready rev-mre-btn button-open-container">
  <span class='my-text'>MORE</span>
  <i class="my-icon fa fa-arrow-down"></i>
  <div class='my-container' style="display:none;">
    TEXT 2
  </div>
</div>