jQuery:select 下拉菜单上的 onclick 事件的自定义函数

jQuery: Custom function for onclick event on select dropdown

正在寻找将自定义 onlick 事件附加到 select 下拉列表的方法。通过单击任一选项,应调用自定义函数。

我的代码包含以下内容HTML:

<select name="database" id="database">
    <option disabled selected> -- select an option -- </option>
    <option>MySQL database format</option>
    <option>PostgreSQL database format</option>
    <option>Oracle database format</option>
    <option>Other format</option>
</select>

基于另一个问题 (Trying to get a jQuery event to Fire onClick on a select/option form) 我创建了这个 JS + jQuery + jQueryUI 代码:

$("#database").selectmenu();
$("#database").change(function() {
    alert("A1");
});

https://jsfiddle.net/1ba470wL/5/

有问题,函数没有被调用,问题出在哪里?

$("#database").selectmenu(); 未定义

https://jsfiddle.net/1ba470wL/2/

我不确定你想要达到什么目的..

$("#database").on("click", function() {
    console.log("custom function");
});

你 fiddle 坏了,因为你缺少一个外部库(你通过 selectmenu() 调用的库)

使用您示例中的 html:

$("#database").on("change", function(){
//Code here
});

不确定您要做什么。

$("#database").on('change', function() {
 var selected_value = $(this).val();
    alert(selected_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select name="database" id="database">
    <option disabled selected> -- select an option -- </option>
    <option value="mysql">MySQL database format</option>
    <option value="postgreSQL">PostgreSQL database format</option>
    <option value="oracle">Oracle database format</option>
    <option value="Other">Other format</option>
</select>

解决方案是将 change 事件更改为 selectmenuchange,这是由 jQueryUI 处理事件的方式不同造成的。

$("#database").selectmenu();
$("#database").on("selectmenuchange",function() {
    alert("A1");
});