jQuery没有从更改时的select语句获取价值 [英] jquery not getting value from select statement on change

查看:132
本文介绍了jQuery没有从更改时的select语句获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的很奇怪,但是我可能缺少一些简单的东西.我有一个简单的select语句,用户可以在其中选择一个值.

This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.

onChange调用了一个函数getDrop2(),当前我正试图让它提醒我选择了哪个选项.

onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.

我的html是:

<select  onChange= "getDrop2()" id = "drop1" >
     <option value="0">All</option>
     <option value="1">Alphabetical</option>
     <option value="2">Brewery</option>
     <option value="3">Style</option>
</select>

我的Javascript是:

My Javascript is:

function getDrop2(){
    var choice = $("#drop1").val()
    alert(choice);

}

警报语句的输出仅为空白.

The output of the alert statement is just blank.

推荐答案

在jQuery中,最好这样做:

In jQuery, you're better off doing something like:

<select id = "drop1" >
     <option value="0">All</option>
     <option value="1">Alphabetical</option>
     <option value="2">Brewery</option>
     <option value="3">Style</option>
</select>

使用以下JavaScript:

With the following JavaScript:

 $(function(){
    $('#drop1').change(function() {
        var choice = $(this).val();
        alert(choice);
    }
  });

想法是jQuery现在将自动将change函数附加到id为"drop1"的select上.通过使用这种模式,您已经将HTML与进行业务逻辑的JavaScript分离了.

The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.

这篇关于jQuery没有从更改时的select语句获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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