简体   繁体   English

jQuery比较选择同级值

[英]JQuery Compare select siblings values

I have 10 dropdown menus, each with 30 or so options. 我有10个下拉菜单,每个菜单都有30个左右的选项。 I'm trying to prevent the same value being selected in any of the menus by using JQuery to compare each select value to its siblings. 我试图通过使用JQuery将每个选择值与其同级进行比较来防止在任何菜单中选择相同的值。 Here's my code, but it ain't workin: 这是我的代码,但无法使用:

$('#select1').change(function() {
    if ($(this).val() == $(this).siblings().val()) {
        alert("OK");
    }
});

As you can see I'm trying to compare the value of #select1 against all it's siblings by using $(this).siblings().val() . 如您所见,我正在尝试使用$(this).siblings().val()#select1的值与其所有同级对象进行比较。 Can't figure out why this won't work. 无法弄清楚为什么这行不通。

$('#select1').change(function() {
    var self = this, 
        t = $(this).siblings().filter(function() {
            return this.value == self.value;
        });
    if (t.length) {
        alert("OK");
    }
});​

FIDDLE 小提琴

I think siblings return a list of elements not a single item, so you need to run a loop 我认为兄弟姐妹返回的元素列表不是单个项目,因此您需要运行循环

$('#select1').change(function() {

    var $select = $(this);

    $(this).siblings().each(function(index){

        if ($(this).val() == $select.val()) {
            alert('ok');
        }
    }
});

try using inArray 尝试使用inArray

$('#select1').change(function() {

    var arr=[];
    $.each($(this).siblings(),function(i,j){
     arr.push($(j).val());
    });
    if ($.inArray($(this).val(),arr)) {
        alert("OK");
    }
});

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

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