引号内的jquery变量名

时间:2015-10-26 17:58:39

标签: javascript jquery

我想使用jquery在select控件中进行选择。搜索的值是jquery变量。我在stackoverflow找到了这个解决方案(可以工作)。

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

但我想在单引号中使用变量来搜索

var target = '2011/1';

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

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

4 个答案:

答案 0 :(得分:2)

您可以将字符串与变量连接:

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

答案 1 :(得分:2)

您可以连接变量值,如下所示:

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

答案 2 :(得分:0)

在ES6中,您可以使用Template strings

$(`#selectbox option[value = '${target}']`)

答案 3 :(得分: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>

相关问题