twitter-bootstrap Twitter Bootstrap SelectPicker onchange 函数未被调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17893433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:43:04  来源:igfitidea点击:

Twitter Bootstrap SelectPicker onchange function not being called

jqueryhtmltwitter-bootstrap

提问by Tim

So I have a simple select list

所以我有一个简单的选择列表

<select id="themes" class="selectpicker">
    <option selected>mkl-ambiance</option>
    <option>default</option>
    <option>ambiance</option>
    <option>blackboard</option>
</select>

and a small snippit of jquery

和一小段 jquery

   $("#themes").change(function() {
        var theme = $("#themes").val();
        editor.setOption("theme", theme);
    });

if I remove class="selectpicker"from the select the call back works as expected. I even added onchange="doMyFunctionand changing $("#themes").change(function() {to function doMyFunction() {and that still didn't work. Is there some bootstrap magic I'm missing to get this to work properly?

如果我class="selectpicker"从选择中删除回调按预期工作。我什至添加onchange="doMyFunction并更改$("#themes").change(function() {function doMyFunction() {,但仍然无效。是否有一些引导魔法让我无法正常工作?

回答by user3086253

This is because Selectpicker generates <ul>and <li>tags and keeps the <select>and <option>aside. It adds 'rel' attribute to each <li>element for you to know which option is selected in relation to the selected <li>.

这是因为 Selectpicker 生成<ul><li>标记并保留<select><option>。它为每个<li>元素添加了 'rel' 属性,以便您了解与所选<li>.

Anyways, you should either use an official onChange event from the Selectpicker plugin, or do something like the following:

无论如何,您应该使用 Selectpicker 插件中的官方 onChange 事件,或者执行以下操作:

$('ul.dropdown-menu.selectpicker li').on('click', function () {
    var selectedValue = $($('select.selectpicker option')[$(this).attr('rel')]).val();
});