使用 Jquery 更改选择值 [英] Change Select value with Jquery

查看:40
本文介绍了使用 Jquery 更改选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Jquery 更改表单中选择"输入的值,但是当它更改时,该更改的函数不起作用.

I'm trying to use Jquery to change the value from a "select" input in a form, but when it changes, the function for that change doesn't work.

HTML:

<select id='select'>
  <option checked value='1' >Option 1</option>
  <option value='2' >Option 2</option>
</select>
<div id='text'>Option 1 selected</div>
<div id='button'>Click to select Option 2</div>

JQuery:

$('#select').change(function(){
    if($(this).val() == '1'){
    $('#text').text('Option 1 selected');
  } else if($(this).val() == '2'){
    $('#text').text('Option 2 selected');
  }
});

$('#button').click(function(){
    $('#select').val('2');
})

CSS:

#button {
  cursor: pointer;
  color: white;
  background: red;
  padding: 5px;
  display: inline-block;
}

演示:https://jsfiddle.net/fdko9nna/

当我单击 #buttondiv 时,它会更改选择字段,但不会执行更改 #text 的函数.
谢谢.

When I click the #buttondiv, it changes the select field, but the function that changes the #text it's not executed.
Thanks.

推荐答案

您需要使用 .change()trigger('change') 触发更改事件> 在您的按钮代码中:

You need to trigger the change event with either .change() or trigger('change') in your button's code:

$('#button').click(function(){
    $('#select').val('2').change();
})

您绑定到 select 的更改事件不会通过单独通过 jQuery 更改值来触发,因此您需要调用 jQuery 的更改事件.

The change event you bound to the select doesn't get triggered by changing the value via jQuery alone, so you need to invoke jQuery's change event.

jsFiddle 示例

这篇关于使用 Jquery 更改选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆