jquery select2 .on("change", function(e) 重置选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17997241/
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-08-26 20:20:49  来源:igfitidea点击:

jquery select2 .on("change", function(e) reset option

javascriptjqueryjquery-select2

提问by Pravat Panda

i am using select2.

我正在使用 select2。

Usage : if a value is "COUNTRY", i want to add a onchange event to the select2, else i want to remove the onchange event as shown below :

用法:如果值为"COUNTRY",我想向 select2 添加一个 onchange 事件,否则我想删除 onchange 事件,如下所示:

var reportLevel = getReportLevel();

if (reportLevel != "COUNTRY") {
    $("#selected_countries").on("change", function(e) {
        prepareGlidModel(e);
    });
} else {
    $("#selected_countries").on("change", function(e) {
    });
}

Issue : Not being able to remove the onchange event, even if the else block is called. Events are called based upon the reportLevelvalue selected in a dropdown.

问题:即使调用了 else 块,也无法删除 onchange 事件。根据reportLevela 中选择的值调用事件dropdown

回答by maverickosama92

try following:

尝试以下操作:

var reportLevel = getReportLevel(),
    // by default unbind/off change event
    $select = $("#selected_countries").off("change");

// and if country then bind it
if (reportLevel == "COUNTRY") {
   $select.on("change", function(e) {
       alert("you selected :" + $(this).val());
   });
}

Working example here: http://jsfiddle.net/JB89B/1/

这里的工作示例:http: //jsfiddle.net/JB89B/1/

回答by Alok Agarwal

i think on else case you want to reset the value to default for this you have to use

我认为在其他情况下你想将值重置为默认值,你必须使用

$("#selected_countries").val('default value')

and if u just want to prevent the default action of onchange event than on else you can write

如果你只是想阻止 onchange 事件的默认操作而不是其他你可以写

e.preventDefault()

this will help

这会有所帮助

回答by Rodrigo Da Rosa Elesbao

You can use off to deatach event handlers from your elements as shown below:

您可以使用 off 从元素中分离事件处理程序,如下所示:

$("#selected_countries").off('change');