我正试图理解onclick事件,但却被弄糊涂了?
我有一个onclick按钮在一个“tab”内容。当我点击这个onclick按钮时,它会打开标记为“tokyo”的正确选项卡,但它不会继续/添加活动类。
第一个选项卡内容中的“我的”按钮是:
<button class="new-btn" onclick="openCity(event, 'Tokyo')">Click Me</button>
我不明白如何告诉它做相同的onclick事件,但添加活动类到“东京”选项卡从这个新的按钮点击?
以下是完整的代码:
<style>
body {font-family: Arial;}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
<button class="new-btn" onclick="openCity(event, 'Tokyo')">Click Me</button>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>
<script>
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
您正在将活动类添加到您的按钮中,而不是添加到活动选项卡中。您可以通过id选择正确的活动选项卡,或者使用选项卡索引而不是城市名称。
document.getElementById(cityName + "-tab").classList.add("active");
// evt.currentTarget.className += " active";
例如:https://jsfidle.net/90h5nwds/