简体   繁体   English

jQuery select2 .on(“更改”,功能(e)重置选项

[英]jquery select2 .on(“change”, function(e) reset option

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. 问题:即使调用了else块,也无法删除onchange事件。 Events are called based upon the reportLevel value selected in a dropdown . 根据dropdown选择的reportLevel值调用事件。

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/

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 这会有所帮助

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM