如何在onclick触发后获取html上的var的值?

时间:2017-05-09 15:52:14

标签: javascript html css dom

在导航栏上,我尝试使用onclick="dismiss(tabName);关闭标签页 。如果我在onclick javascript函数onclick="dismiss('Paris');上添加div名称,我可以关闭名为Paris的选项卡。

但是这使我只能关闭巴黎的标签。我想关闭所有打开的标签。

如何动态接收当前有效标签的值,并将其传递给onclick="dismiss(tabName);以使我能够关闭任何标签?

此处的工作示例https://jsfiddle.net/av2o94bL/

这是javascript函数:

function openCity(evt, cityName, ThirdValue) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
   }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the link that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
  var text = document.getElementById(cityName);
  text.innerHTML = text.innerHTML.replace('{var}',thirdValue);

}
function dismiss(cityName)
    {
    document.getElementById(cityName).style.display='none';
};

这是html:

<ul class="tab">
  <li><a href="javascript:void(0)" class="tablinks" onclick="openCity(event, 'London', 'capital')">London</a></li>
  <li><a href="javascript:void(0)" class="tablinks" onclick="openCity(event, 'Paris', 'France')">Paris</a></li>
  <li><a href="javascript:void(0)" class="tablinks" onclick="openCity(event, 'Tokyo', 'Japan')">Tokyo</a></li>
  <li><a id="dismiss"  class="tablinks" onclick="dismiss('Paris');"><b>close tab</b></li>
</ul>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the {var} city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of {var}</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of {var}.</p>
</div>

2 个答案:

答案 0 :(得分:1)

只需在变量

中保存当前标签的名称即可
var currentTab = null;

function openCity(evt, cityName, ThirdValue) {
   ...
   currentTab = cityName;
}

function dismiss()
{
   document.getElementById(currentTab).style.display='none';
};

请参阅https://jsfiddle.net/cxwqrdgp/9/

答案 1 :(得分:0)

答案就在你的问题中。您已将其他选项卡设置为与当前选项卡不同。你可以简单地使用变量来存储它,或者你只需​​要一个方法来获得像这样的活动标签

function getActiveTab(){
    var tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
      if(tabcontent[i].style.display!=="none"){
            return tabcontent[i].id;
      }
    }
}