我想分别为每个选项卡调用函数。
像function openCity(event, 'London')
和function openCity(event, 'Paris')
我是JavaScript新手,正在尝试寻找解决方案。 这是我的代码,这种方式很好用,如何单独进行呢?
function openCity(evt, cityName) {
// 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 button that opened the tab
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
<!-- Tab links -->
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
</div>
<!-- Tab content -->
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
答案 0 :(得分:0)
你好!
我认为您必须根据您的文章在head
标记中设置两个脚本文件才能添加Ajax功能。就是这样...
<script type="text/javascript" src="javascript/ajax_openCity.js"> </script>
此脚本链接将AJAX功能脚本命令链接到当前主页。因此,此方法不得对php文件进行任何更改。
我认为您必须参考这本书。我向您推荐这本书: Charles Wyke-Smith的“ Scriptin'with JavaScript and Ajax” 。 >
答案 1 :(得分:0)
将事件带出DOM并在脚本中运行:它更好,因为这样更有效
//execute scripts when DOM ready !
document.addEventListener("DOMContentLoaded", function (event) {
var city;//define your city var
//find all tab classes with queryselector
const buttons = document.querySelectorAll(".tablinks")
//loop though them and add click event
for (const button of buttons) {
button.addEventListener('click', function(event) {
city = this.innerHTML;//find city name better to use data-attribute
openCity(event,city);
})
}
});
保留原始的开放城市功能
从所有标签中删除onclick ..立即添加尽可能多的标签