2015-10-26 74 views
1

我想在使用jquery的选择控件中进行选择。搜索的值是一个jQuery变量。我发现这个解决方案(工作)在这里在stackoverflow。引号中的jquery变量名

$("#selectbox option[value = '2011/1']").prop('selected', true); 

,但我想用一个变量在单引号搜索

var target = '2011/1'; 

$("#selectbox option[value = 'target']").prop('selected', true); 

我曾尝试使用和不使用单引号,但没有成功多种组合。那么解决方案是什么?

+0

这是一个字符串,你创建像正常的字符串。 –

回答

2

你可以只连接具有一个变量的字符串:

$("#selectbox option[value = '"+target+"']").prop('selected', true); 
2

,可以串联变量值,就像这样:

$("#selectbox option[value ='" + target + "']").prop('selected', true); 
0

尝试转义字符"/"target变量与\\

var target = "2011\\/1"; 
 

 
$("#selectbox option[value=" + target + "]").prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
 
</script> 
 
<select id="selectbox"> 
 
    <option value="2010/1">2010/1</option> 
 
<option value="2011/1">2011/1</option> 
 
</select>