jQuery 检查值是否不在数组中

oso*_*den 6 arrays jquery

试图让它发挥作用:

var instance_name = $('#instance_name').val();
$("#instance_name").on("blur", function(e){
    if (!~$.inArray(instance_name, not_allowed)) {
        $("#instance_alert").html("<font color=green>Instance does not exists. Please continue</font>");
    } else {
        $("#instance_alert").html("<font color=red>Instance exists. Please try another one.</font>");
    }
Run Code Online (Sandbox Code Playgroud)

但无济于事..(研究了如何使用 jQuery 检查值是否不在数组中

任何想法为什么它仍然继续说Please continue Kindly

Ang*_*ngu 5

你可以使用这个:请$.inArray

if(jQuery.inArray("test", not_allowed) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
} 
Run Code Online (Sandbox Code Playgroud)


Kam*_*han 3

首先,instance_name由于您在模糊事件之外保存该值,因此模糊时不会更新 的值。

因此,您需要var instance_name = $('#instance_name').val();在模糊事件侦听器内移动。在事件侦听器内部时,您可以使用简写$(this).val()来获取值。

对于条件,使用indexOf,如果某个值不在搜索数组中,则返回-1,否则返回正在搜索的值的位置索引(即0,1,2...)。

代码:

var not_allowed = ["test", "noah", "help", "demo"];
$("#instance_name").on("blur", function (e) {
    // $(this).val() is the value of #instance_name.
    if (not_allowed.indexOf($(this).val()) > -1) {
        $("#instance_alert").html("<font color=red>Instance exists. Please try another one.</font>");
    } else {
        $("#instance_alert").html("<font color=green>Instance does not exists. Please continue</font>");
    }
});
Run Code Online (Sandbox Code Playgroud)