切换类不起作用

时间:2016-09-09 07:38:39

标签: javascript

我有这样的跨度:

<span class="read_more"> Read More </span>

和这样的一些div:

<div class="tab_inner">
    .
    .
    .
    .
</div>

如何为他们切换课程(active

这是我的代码:

var showTab = document.getElementsByClassName("read_more");
var tabContent = document.getElementsByClassName("tab_inner");

function showTabContent(event) {
    for (var i = 0; i < showTab.length; i++) {
        showTab[i].addEventListener('click', function() {
            tabContent.toggle('active');
        });
    }
}

我无法通过document.getElementsByClassName获取DOM  或函数中的document.getElementsByTagName。只是document.getElementById在函数中工作。

我该怎么办?

2 个答案:

答案 0 :(得分:2)

您只能在单个元素上的classList上运行切换。我修改了下面的代码

var showTab = document.getElementsByClassName("read_more");
var tabContent = document.getElementsByClassName("tab_inner");

function showTabContent() {
  for (var i = 0; i < showTab.length; i++) {
    (function(index) {
      showTab[i].addEventListener('click', function() {
        tabContent[index].classList.toggle('active'); // I have assumed each read more has a corresponding tab content
      });
    })(i);
  }
}

showTabContent();
.tab_inner.active {
  color: red;
}
<div class="read_more">read more</div>
<div class="tab_inner">tab content</div>
<div class="read_more">read more</div>
<div class="tab_inner">tab content</div>

答案 1 :(得分:1)

您可以调用Element.classList的方法toggle(),这是一个只读属性,它返回元素类属性的实时DOMTokenList集合。

代码:

&#13;
&#13;
var showTab = document.getElementsByClassName('read_more'),
    tabContent = document.getElementsByClassName('tab_inner');

Array.prototype.forEach.call(showTab, function(elem, index) {
  elem.addEventListener('click', function() {
    tabContent[index].classList.toggle('active'); 
  });
});
&#13;
.read_more {
    cursor: pointer;
}
.tab_inner.active {
  color: red;
}
&#13;
<span class="read_more">Read More</span>
<div class="tab_inner">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam, dignissimos.</p>
</div>

<span class="read_more">Read More</span>
<div class="tab_inner">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati quam dolor quae error eligendi numquam ipsum. Assumenda modi, explicabo.</p>
</div>
&#13;
&#13;
&#13;

另请注意,您可以通过调用Array的forEach()方法迭代类似数组的HTMLCollection