我有以下网址
search.php?card=Xcel&cat=1
以及我的搜索表单中的以下内容
<div class="icard" >
<select name="card" id="card">
<option value="Xplore">Xplore card</option>
<option value="Xpand">Xpand card</option>
<option value="Xcel">Xcel card</option>
</select>
</div>
<div class="icat" >
<select name="cat" id="cat">
<option value="1">Health</option>
<option value="3">Fitness</option>
<option value="2">Travel & Leisure</option>
<option value="4">Wellness & Spa</option>
<option value="5">Security & Techology</option>
<option value="6">Others</option>
</select>
</div>
使用jquery,基于url中的值
?card=Xcel
,我想将selected ="selected"
添加到第3个选项,现在它变为<option value="Xcel" selected ="selected">Xcel card</option>
我尝试了以下内容但没有成功
var val = location.href.match(/[?&]card=(.*?)[$&]/)[1];
$('#card').val(val);
非常感谢任何帮助
答案 0 :(得分:1)
您可以正确地使用此功能获取查询值,location.href.match
可能会出错:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
获得card
值:
var query = getParameterByName('card');
然后检查query
是否等于选项:
$('#card').change(function(){
if($(this).val() == query){
alert('its equal to query');
}
});
<强> JSFiddle 强>
OR 检查选项等于查询:
$("#card option").each(function(){
if ($(this).val() == query) {
$(this).attr('selected', 'selected');
}
});
<强> JSFiddle 强>
或强>
$('#card option[value="'+query+'"]').attr('selected','selected');
<强> JSFiddle 强>
答案 1 :(得分:0)
使用以下代码获取在url中传递的选定选项:
<script>
function findvalue(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
$("#card option[value='" + findvalue("card") + "']").attr("selected", "selected");
$("#cat option[value='" + findvalue("cat") + "']").attr("selected", "selected");
</script>
答案 2 :(得分:0)
您可以使用以下代码
var q = "?card=Xcel";
var val = q.match(/card=([^']+)/)[1];
$("#card").val(val)
$("#card [value='" + val +"']").attr('selected', 'selected')
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="icard" >
<select name="card" id="card">
<option value="Xplore">Xplore card</option>
<option value="Xpand">Xpand card</option>
<option value="Xcel">Xcel card</option>
</select>
</div>
<div class="icat" >
<select name="cat" id="cat">
<option value="1">Health</option>
<option value="3">Fitness</option>
<option value="2">Travel & Leisure</option>
<option value="4">Wellness & Spa</option>
<option value="5">Security & Techology</option>
<option value="6">Others</option>
</select>
</div>
&#13;