Removing element from link ID for jQuery tab script
I have a jQuery tab script that gets content from a PHP file defined开发者_Python百科 by the link and parses it to a div element. The ID for each link is used to pull content from the correct file however type_ is needed in the link ID for the tabs to work which then doesn't pull content from the right place. How can I resolve this issue?
This is my current jQuery code:
function load(url){
$.ajax({
url:url,
success:function(message){
$("#content").html(message);
}
});
}
$(document).ready(function(){
$("[id^=type_]").click(function(){
type=$(this).attr("id");
url=""+type+".php";
$("[id^=type_]").removeClass("selected");
$("#"+type).addClass("selected");
load(url);
return false;
});
$("#type_search").click();
});
This is my HTML code:
<ul>
<li><a id="type_tab1" href="javascript:void(null);">Tab1</a></li>
<li><a id="type_tab2" href="javascript:void(null);">Tab2</a></li>
<li><a id="type_tab3" href="javascript:void(null);">Tab3</a></li>
</ul>
From your description, I assume you mean the content is located at tab1.php
, tab2.php
, etc and the problem is with your type_
prefix in the ID.
Option #1 - Most like your code
I don't think you need type_
in the id. Seems like you could accomplish the same thing with a class='tab'
on each of your anchors like
<li><a id="tab1" class="tab" href="javascript:void(null);">Tab1</a></li>
and then do
$('.tab').click(function() {
var tabId = $(this).attr("id");
var url=""+tabId+".php";
$('.tab').removeClass("selected");
$('#' + tabId).addClass("selected");
load(url);
return false;
}
Option #2 - Cleaner and makes more sense
There's no reason to overload the ID attribute with the url of your content. Try:
<li><a id="tab1" class="tab" href="/path/to/content/tab1.php">Tab1</a></li>
Normally, this would take you to the content, but you can prevent the default behavior by:
$('.tab').click(function(event) {
// Prevent actually going to the content
event.preventDefault();
// Adjust tabs
var $currentTab = $(this);
$('.tab').removeClass("selected");
$currentTab.addClass("selected");
// Load content from the href attribute of the tab
load($currentTab.attr("href"));
return false;
}
Option #3 - This is already a JQuery Extension
Have you considered using JQuery UI Tabs? http://jqueryui.com/demos/tabs/ I've found the demo site to be a bit wonky sometimes, but JQuery UI is very popular, stable, and flexible. There is an option to load content via AJAX.
精彩评论