Javascript jQuery onchange 选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7806855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:40:24  来源:igfitidea点击:

jQuery onchange select option

javascriptjquery

提问by Manuel van Rijn

Let's say I have this HTML:

假设我有这个 HTML:

<select id='list'>
    <option value='1'>First</option>
    <option value='2'>Second</option>
    <option value='3'>Third </option>
</select> 
<input type ="text" id="text"/>

and then this JavaScript

然后这个 JavaScript

 //other variables are also declared here
    var x1 = 5;
    var x2 = 10;
    var value = x1 * x2;
    var list_value =$("#list").change(function() {
             $(this).val();
 // just an example of how i want the function in the variable 
    });
    var nwval = value * list_value;
      $('#text').val(nwval);
// some long piece of code 
// i'm also using the list_value value somewhere in the long piece of code..

I want the val in the textbox to change as the user selects an option, I know it'll work if I wrap the change event around it, but is there any way to go about this while keeping it as that variable list_value?

我希望文本框中的 val 在用户选择一个选项时发生变化,我知道如果我将更改事件包装在它周围它会起作用,但是有什么办法可以做到这一点,同时保持它作为该变量list_value

回答by Manuel van Rijn

var x1 = 5;
var x2 = 10;
var value = x1 * x2;
var nwval;
$("#list").change(function() {
    nwval = value * $(this).val();
    $('#text').val(nwval);
});

回答by Sedat Ba?ar

$('#text').val($('option:selected').text());
$('#list').change(function(){

        $('#text').val($('option:selected').text());
})

check from here http://jsfiddle.net/QrHUN/

从这里检查http://jsfiddle.net/QrHUN/

回答by Hailwood

Wrapping the change event is the better way as it creates a closure, you could use global variables as below, but you would be better (imho) to simply grab the value again futher down.

包装更改事件是更好的方法,因为它创建了一个闭包,您可以使用如下全局变量,但您最好(恕我直言)简单地再次获取该值。

You could technically do (although a bad idea as it is global variables):

从技术上讲,您可以这样做(尽管这是一个坏主意,因为它是全局变量):

var x1 = 5;
var x2 = 10;
var value = x1 * x2;
var list_value = 1;
$("#list").change(function() {
    list_value = $(this).val();
    var nwval = value * list_value;
    $('#text').val(nwval); 
});

回答by epascarello

this returns a jQuery object, not a value.

这将返回一个 jQuery 对象,而不是一个值。

var list_value =$("#list").change(function() {  

If you want the value outside of the code, you would need to do something like this

如果你想要代码之外的值,你需要做这样的事情

var list_value = 0;
var sel = $("#list").change(function() {
         list_value = $(this).val();
}).change();
var nwval = value * list_value;
$('#text').val(nwval);

BUT the onchange event will never update the page, just that variable!

但是 onchange 事件永远不会更新页面,只会更新那个变量!