Onchange选择运行功能

onchange select run function

本文关键字:功能 运行 选择 Onchange      更新时间:2023-09-26
<select onchange="alert();">
            <option>d</option>
            <option>de</option>
            <option>dewe</option>
            <option>dewee</option>
        </select>

我想让一个<select>元素的onchange事件显示一个警告,但是它不工作。

你知道怎么回事吗?

我假设您的问题是alert()呼叫显示未定义而不是<select>的值。

如果您想查看<select>的值,请这样做:

<select onchange="alert(this.value);">
    <option>d</option>
    <option>de</option>
    <option>dewe</option>
    <option>dewee</option>
</select>

jsfiddle例子


或者,如果你正在使用jQuery,你可以这样做:

//This is an anonymous function that calls itself with the jQuery object as an argument
//This allows you to use the `$` when making jQuery calls but the code
//will run without modification if jQuery is in noConflict() mode
(function($) {
    //This is the important part
    //Here, we bind to the change event and alert the value
    $('select').change( function(e) {
        alert($(this).val());
    });
})(jQuery)
示例2

这应该可以工作,但您也可以尝试在您的页面上包含jQuery

$(function(){
   $("select").change(function(){
      alert($(this).val());
   });
});

如果你想让alert函数工作,你应该给一个字符串作为参数…