JavaScript显示最后一个选项卡

JavaScript show last tab

本文关键字:选项 最后一个 显示 JavaScript      更新时间:2023-09-26

我创建了4个标签,一次只显示1个,但是如果我在标签4的表单中发布了一些东西,那么标签1就会变得活跃,但我希望它能自动显示标签中发布的东西。

下面是我的代码:
<script src="../js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
    
    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });
});
</script>

<center>
  <ul class="tabs">
    <li><a href="#tab1">Tab 1</a></li>
    <li><a href="#tab2">Tab 2</a></li>
    <li><a href="#tab3">Tab 3</a></li>
    <li><a href="#tab4">Tab 4</a></li>
  </ul>
  <div class="tab_container"><br><br><br>
    <div id="tab1" class="tab_content">
<center><h2>Tab 1</h2></center>
                </div>
                    <div id="tab2" class="tab_content">
<center><h2>Tab 2</h2></center>
                </div>
                    <div id="tab3" class="tab_content">
<center><h2>Tab 3</h2></center>
                </div>
                    <div id="tab4" class="tab_content">
                    <?php
                    $getmessage = $_POST["message"];
                    if($getmessage != null) {
                        echo"Thanks for posting the text!";
                    } ?>
<center><form method="post" name="form4"><input type="text" id="form4" name="message" placeholder="Type a text here"><br><input type="submit" value="Post text"></form></center>
                </div>
</div></center>
</center>

因此,当我在标签4中提交表单时,我到达标签1,我手动必须转到标签4才能看到我的echo显示的消息。我需要它自动转到提交表单的选项卡,但我不知道如何做到这一点。

向表单添加另一个输入(隐藏)元素,例如active_tab,并在单击选项卡时使用活动选项卡填充它。从$_POST中获取该值并相应地设置默认选项卡。

步骤1:添加输入元素

<input type="hidden" name="active_tab" />

步骤2:更新输入的值

$("ul.tabs li").click(function() {
    $('input[name="active_tab"]').val( $(this).index() );
    //your remaining code as is
    //...

步骤3:根据post值

设置默认选项卡
$(document).ready(function() {
    //Default Action
    var tabNum = "<? echo !empty($_POST['active_tab']) ? $_POST['active_tab'] : 0; ?>";
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li").eq(tabNum).addClass("active").show(); //Activate the tab
    $(".tab_content").eq(tabNum).show(); //Show the tab content

给你的表单action="#tab4"(确保页面重新加载)。在JS脚本中还需要添加从url:

读取的代码
var hash = (window.location.hash).substr(1) || null;
if(hash == "tab4")
    $(".tab_content:last").show();