在html中,当创建选项卡时,我可以将Paris选项卡设置为活动的(在html中用“style=”display:block;“硬编码)。因此,当页面加载时,活动选项卡(Paris)将显示。
问题
当我点击不同的标签(伦敦)并点击刷新,它再次显示巴黎。我如何才能点击刷新并显示当前活动的选项卡的信息?而不是将我带回定义的选项卡。也许javascript或jquery可以解决我的问题?
<!DOCTYPE html>
<html>
<head>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')">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>
</div>
<div id="Paris" class="tabcontent" style="display: block;>
<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";
}
</script>
</body>
</html>
柱塞视图
示例图像
当前在伦敦,如果我点击刷新,它应该显示伦敦的详细信息。如果是巴黎或东京,也会起作用。
这是你贴出的一个修改过的柱塞:
// your code
// After you have your tab selected save it to a cookie (change expiration to something that makes sense to you.
document.cookie = "cityName="+cityName+"; expires=Thu, 18 Dec 2090 12:00:00 UTC; path=/";
}
document.addEventListener("DOMContentLoaded", function(){
// When you load the page check if the cookie is there and read it back
var selectedCity = getCookie("cityName");
// if there is a selected city then select it. Notice that I added id's to each link with the city name.
if (selectedCity != ""){
document.getElementById(selectedCity).click();
}
});
// Helper function to get the cookie value from the document.cookie string.
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
https://plnkr.co/edit/scrfbsfrgdq0wpki9cmb?p=预览
希望有帮助!