繁体   English   中英

选择更改jQuery不起作用

[英]select on change jquery not working

我有以下似乎无效的代码:

 $('.chosen-select').on('change', function() { if ('.chosen-select'.value == '1') { $("#tips").html("the color that you want to add."); } else if ('.chosen-select'.value == '2') { $("#tips").html("the text that you want to add."); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="tips"></div> <select class="chosen-select" style="width:290px;" name="option"> <option value="1">change background colour</option> <option value="2">insert text</option> <option value="3">insert arrow</option> </select> 

我的Web浏览器控制台没有给我任何错误。 该代码假定基于更改选择选项值来更改div的html。

'.chosen-select'.value无效,因为它既不是有效的jQuery表达式也不是JavaScript。 而是使用$('.chosen-select').val()this.value$(this).val()

jsFiddle示例

使用if($(this).val() == '1') {不像if('.chosen-select'.value == '1')

  $(function() { $('.chosen-select').on('change', function() { if($(this).val() == '1') {$("#tips").html( "the color that you want to add.");} else if($(this).val() == '2') {$("#tips").html( "the text that you want to add.");} }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="tips"></div> <select class="chosen-select" style="width:290px;" name="option"> <option value="1">change background colour</option> <option value="2">insert text</option> <option value="3">insert arrow</option> </select> 

下面的表达式不会产生您想要的结果:

'.chosen-select'.value

它尝试访问undefinedString对象的value属性,因为字符串没有这样的属性。

在更改事件处理程序函数中,您可以充分利用以下事实: this引用了<select>元素:

var selectedValue = this.value; // get value from select element

或者,使用jQuery的.val()函数获取值:

var selectedValue = $(this).val();

暂无
暂无

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

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