SoFunction
Updated on 2025-02-28

Use jquery to implement the tab switching instance code of div

jQuery implements Tab switching. The simple effect of writing with jQ not long ago is now written in jQ:
HTML code:
Copy the codeThe code is as follows:

<div >
<div >
<h3><span class="selected">Latest Comments</span><span>Recent Hot Comments</span><span>Random Articles</span></h3>
</div>
<div >
<ul><li>1234567890-1</li></ul>
<ul class="hide"><li>1234567890-2</li></ul>
<ul class="hide"><li>1234567890-3</li></ul>
</div>

</div>

css code:
Copy the codeThe code is as follows:

#sidebar-tab{border:1px solid #ccf;margin-bottom:1.5em;overflow:hidden;}
#tab-title h3{color:#666;font-size:15px;font-weight:400;}
#tab-title .selected{color:#356aa0;border-bottom:0px;} /*Style when the title is selected*/
#tab-title span{padding:5px 9px 5px 10px;border:1px solid #ccf;border-right:0px;margin-left:-1px;cursor:pointer;}
#tab-content .hide{display:none;} /*By default, let the first piece of content be displayed, the rest are hidden*/
#tab-content ul{padding:5px 10px;overflow:hidden;}
#tab-content ul li{padding-top:5px;height:20px;}

jQ code:
Copy the codeThe code is as follows:

<script language="javascript">
$('#tab-title span').click(function(){
$(this).addClass("selected").siblings().removeClass();//removeClass means to delete other current classes; only the current object has addClass("selected"); siblings() means to the same level element of the current object, removeClass means to delete;
$("#tab-content > ul").hide().eq($('#tab-title span').index(this)).show();
});
</script>

It is very convenient to write with jQ; first, find the child elements in the ID and add event click to introduce the function; after finding the same element, removeClass(); let other elements of the same level display: "none" when displaying this;

Here is the original jQ code:

Copy the codeThe code is as follows:

<script>

$('#tab-title span').click(function(){ $(this).addClass("selected").siblings().removeClass(); $("#tab-content > ul").slideUp('1500').eq($('#tab-title span').index(this)).slideDown('1500')
});
</script>

When you trigger the current event and click on the current event, it will also trigger it; there is no need to click on the current event and also trigger the event (this);