【问题标题】:Cannot get selected value from dropdown within the bind function jQuery无法从绑定函数jQuery中的下拉列表中获取选定的值
【发布时间】:2018-01-23 07:41:34
【问题描述】:

下面是我的伪代码

$("#oneElement").bind(
    "change",
    {
        field:$("#theDropDownList").find("option:selected").text()
    },
    theFunction
);

$("#oneElement") 发生变化时,它会调用theFunction (event) {},我希望在event.data.field 中找到从$("#theDropDownList") 中选择的值。

但是即使在多次更改$("#oneElement") 之后,field 也从未在我加载网页时更新。

**编辑:** theFunction 看起来像

function theFunction(event) {
    console.log(event.data.field);
    //do whatever
} 

欢迎大家帮忙!

【问题讨论】:

  • 你能告诉我们theFunction是什么吗?我们无法判断您是否在其中正确操作。
  • bind 在 jQuery 中已弃用,因此即使是伪代码,看到它也有点奇怪。 (另外,鉴于它具有与 JavaScript bind不同的功能,这让事情变得更糟)
  • 数据可能是在绑定时间内计算的,而不是在事件被捕获时计算的。我稍后会详细说明
  • @Tibrogargan 如果不使用bind,您将如何获得相同的结果?
  • 发生这种情况是因为 eventData 按原样传递给函数,它不会在事件触发时进行评估,因此您将获得 bind 时的值叫

标签: javascript jquery events jquery-events


【解决方案1】:

对象值在绑定期间计算一次,并在事件触发时传递给函数。如果您想实时获取该值,则不应在绑定时将其作为数据传递。从函数中获取它,因为它在事件触发后执行。

$("#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"/>

【讨论】:

  • 最终采用这种方式并将bind 函数(显然已弃用)更改为on
  • 在 v3 中已弃用。您可能需要阅读本文了解更多详情elijahmanor.com/…
【解决方案2】:

建议您使用on,而不是已弃用的bind

你可以这样做:

$("#oneElement").on("change", theFunction);

function theFunction() {
  var someValue = $("#theDropDownList").find("option:selected").text();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2018-01-25
    • 2022-01-21
    • 2019-03-07
    相关资源
    最近更新 更多