无法从绑定函数中的下拉列表中获取选定值 jQuery
Cannot get selected value from dropdown within the bind function jQuery
下面是我的伪代码
$("#oneElement").bind(
"change",
{
field:$("#theDropDownList").find("option:selected").text()
},
theFunction
);
当 $("#oneElement")
发生变化时,它会调用 theFunction (event) {}
,我希望从 $("#theDropDownList")
中的 event.data.field
中找到选定的值。
但是 field
从我加载网页开始就永远不会更新,即使在多次更改 $("#oneElement")
之后也是如此。
**编辑:** theFunction
看起来像
function theFunction(event) {
console.log(event.data.field);
//do whatever
}
欢迎大家帮忙!
我建议您使用 on
,而不是已弃用的 bind
。
你可以这样做:
$("#oneElement").on("change", theFunction);
function theFunction() {
var someValue = $("#theDropDownList").find("option:selected").text();
}
对象值在绑定期间计算一次,并在事件触发时传递给函数。如果您想实时获得值,则不应在绑定时将其作为数据传递。从函数内部获取它,因为它在事件触发后执行。
$("#oneElement").bind(
"change",
{
field:$("#theDropDownList").find("option:selected").text()
},
function(event){
//bind time
console.log(event.data.field);
//run time
console.log($("#theDropDownList").find("option:selected").text());
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="theDropDownList">
<option value="1">text 1</option>
<option value="3">text 2</option>
<option value="3">text 3</option>
</select>
<input type="text" id="oneElement"/>
下面是我的伪代码
$("#oneElement").bind(
"change",
{
field:$("#theDropDownList").find("option:selected").text()
},
theFunction
);
当 $("#oneElement")
发生变化时,它会调用 theFunction (event) {}
,我希望从 $("#theDropDownList")
中的 event.data.field
中找到选定的值。
但是 field
从我加载网页开始就永远不会更新,即使在多次更改 $("#oneElement")
之后也是如此。
**编辑:** theFunction
看起来像
function theFunction(event) {
console.log(event.data.field);
//do whatever
}
欢迎大家帮忙!
我建议您使用 on
,而不是已弃用的 bind
。
你可以这样做:
$("#oneElement").on("change", theFunction);
function theFunction() {
var someValue = $("#theDropDownList").find("option:selected").text();
}
对象值在绑定期间计算一次,并在事件触发时传递给函数。如果您想实时获得值,则不应在绑定时将其作为数据传递。从函数内部获取它,因为它在事件触发后执行。
$("#oneElement").bind(
"change",
{
field:$("#theDropDownList").find("option:selected").text()
},
function(event){
//bind time
console.log(event.data.field);
//run time
console.log($("#theDropDownList").find("option:selected").text());
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="theDropDownList">
<option value="1">text 1</option>
<option value="3">text 2</option>
<option value="3">text 3</option>
</select>
<input type="text" id="oneElement"/>