2013-07-04 73 views
0

我想將下拉列表設置爲在URL中的sortby中找到的值。我不知道如何從URL使用JQuery獲取查詢字符串,不jQuery有內置的東西?獲取查詢字符串值並自動選擇下拉選項

URL: http://www.test.com/search.php?h=454&sortBy=books&nan=4812 

<select class="SearchSortingList"> 
    <option value="tires">5tires and stuff</option> 
    <option value="cars">5cars and stuff</option> 
    <option value="books">5books and stuff</option> 
    <option value="kites">5kites and stuff</option> 
</select> 

這就是我所在的地方,我只是需要一些幫助。

// select books dropdown since the value of sortby (in url) is books 
$('select[name="SearchSortingList"]').val(JQUERY_GRABQUERYSTRINGVALUE('sortBy')); 
+0

這個函數從url中抽取參數到一個數組:http://jquery-howto.blogspot.de/2009/09/get-url-parameters-values-with-jquery.html – abimelex

回答

1

據我知道有沒有,但你可以使用正則表達式來提取sortby值

var val = location.href.match(/[?&]sortBy=(.*?)[$&]/)[1]; 
$('.SearchSortingList').val(val); 
+0

你需要排除'#'從比賽也是。 – mishik

2

嘗試:

var sortBy = window.location.href.match(/[?&]sortBy=([^&#])*/)[1]; 
$('select.SearchSortingList option[value="' + sortBy + '"]').prop("selected", true); 

select[name="SearchSortingList"]應該select.SearchSortingList因爲SearchSortingList是實際上是一個階級而不是一個名字。