简体   繁体   English

jQuery onchange选择选项不起作用

[英]jquery onchange select option not working

Currently my code looks like this, 目前,我的代码看起来像这样,

$("#select").change(function() {
    var thes = $(this).attr('value');
    var next = $('option[:selected]').next().attr('value');
    alert(next);
});

and my select looks like this 我的select看起来像这样

<select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

I tried using alert the variable thes and it pops up but when I use the variable next it won't. 我尝试使用alert变量thes并弹出,但是当我next使用该变量时则不会。 What is wrong with my code? 我的代码有什么问题? Please help. 请帮忙。

Change 更改

'option[:selected]'

To

'option:selected'

So: 所以:

$("#select").change(function() {
    var thes = $(this).attr('value');
    var next = $('option:selected').next().attr('value');
    alert(next);
});

Check this fiddle 检查这个小提琴

Please note that this would give the next() for the last index as undefined . 请注意,这会将最后一个索引的next()赋予undefined You may want to handle that appropriately. 您可能需要适当地处理。

Read more on the :selected selector here :selected选择器上阅读更多信息

You missed this 你错过了

var next = $('option:selected').next().attr('value');

JSFIddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM