我正在尝试转换
var target = $(this).attr('href')
$(target).addClass('active');
使用
let target = this.getAttribute('href')
目标是“#tab3”
target.classList.add('active');
结果无法读取未定义的属性添加
function tabControl() {
const tabs = document.querySelector('.tabs');
if (!isHidden(tabs)) {
const tabItems = tabs.querySelectorAll('a');
for (const tabItem of tabItems) {
tabItem.addEventListener('click', function(event) {
event.preventDefault();
let target = event.target.getAttribute('href'),
tabs = closest(this, '.tabs');
buttons = tabs.querySelectorAll('a'),
item = closest(tabs, '.tabbed-content').querySelector('.item');
buttons[0].classList.remove('active');
item.classList.remove('active');
this.classList.add('active');
target.classList.add('active');
});
}
任何帮助/解释将不胜感激!
html
<article class="tabbed-content">
<nav class="tabs">
<ul>
<li><a href="#tab1" class="active tab">TAB 1</a></li>
<li><a href="#tab2" class="tab">TAB 2</a></li>
<li><a href="#tab3" class="tab">TAB 3</a></li>
</ul>
</nav>
<section id="tab1" class="item active" data-title="Tab 1">
<div class="item-content">
<p>Hello from tab1</p>
</div>
</section>
<section id="tab2" class="item" data-title="Tab 2">
<div class="item-content">
<p>Hello from tab 2</p>
</div>
</section>
<section id="tab3" class="item" data-title="Tab 3">
<div class="item-content">
<div class="materials-container">
<p>Hello from tab 3</p>
</div>
</section>
</article>
答案 0 :(得分:1)
您的代码如下:
const yourElem = document.querySelector('yourSelector');
yourElem.classList.add('yourClassName')
答案 1 :(得分:0)
javascript中的经典方法如下:
this.className = this.className + " active";