我想从选定的表单值构建字符串或'url'。我不想在任何地方处理表单,它只是将一组选项中的字符串拼凑在一起。
我有一个选择班级
<div id="colorselect">
<select class="selectpicker" data-size="5">
<option>red</option>
<option>blue</option>
</select>
</div>
默认为“红色”,当我更改为“蓝色”时,我可以通过在控制台中输入来查看它...
$( "#colorselect.select option:selected" ).val();
给了我
"blue"
然后我将.val()设置为变量
var urlColor = $( "#colorselect.select option:selected" ).val();
and pass to a function
function urlGenerator(urlColor){
var url = 'http://localhost/pixacca/' + urlColor;
// Passes the url into the textarea
$( "#output" ).val(url);
}
当我点击按钮时,它会返回红色而不是蓝色?
<a class="btn btn-lg btn-default" id="process" href="#" role="button">Generate</a>
<div class="output"></div>
$("#process").click( function() {
urlGenerator(urlColor)
});
答案 0 :(得分:3)
将$( "#colorselect.select option:selected" ).val()
放在函数中:
function urlGenerator(){
var url = 'http://localhost/pixacca/' + $( "#colorselect.select option:selected" ).val();
$( "#output" ).val(url);
}
如果为变量赋值,变量不会自动更新。
换句话说,
var urlColor = $( "#colorselect.select option:selected" ).val();
表示:声明变量urlColor
,然后为其分配当前返回的$( "#colorselect.select option:selected" ).val()
(即使返回值可能稍后更改)。
此外,该功能可以简化为
function urlGenerator(){
$('#output').val('http://localhost/pixacca/'+$('#colorselect select').val());
}
由于value
元素的select
属性代表所选value
的{{1}}。