Defining selected tab by url in jQuery tab script
I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. If #type is in the URL the tab that corresponds to that type appears selected. However, If a query is also in the url (#type/query/) the tab isn't selected. With my code below, how can I make it so it will ignore everything after /query/? I hope you can understand what I'm trying to describe.
My jQuery script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
开发者_StackOverflow var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
The slightly clumsy way I came up with is:
$('a').each(
function(){
var url = this.href;
var hashAt = url.indexOf('#');
var nextSlashAt = url.indexOf('/',hashAt);
var url = url.substring(0,nextSlashAt);
var tab = url.substring(hashAt);
$(this).text(url + " (" + tab + ").");
});
JS Fiddle demo.
Obviously rather than iterating through the a
elements, you'll want to assign the url
variable to the window.location;
, but from then on it should be easily adapted to your needs, I think.
References:
indexOf()
.substring()
.
精彩评论