0

I have an Asp.Net user control that I've created. For simplicity some of the html has been removed.

<asp:Panel ID="PanelInputControl" runat="server" CssClass="input-control input-period">
    <div  ID="InputWrapperMonth" runat="server" class="input-wrapper input-month">
        <asp:TextBox ID="TextBoxMonth" runat="server"
            MaxLength="2">
        </asp:TextBox>
    </div>
    <div  ID="InputWrapperYear" runat="server" class="input-wrapper input-year">
        <asp:TextBox ID="TextBoxYear" runat="server"
            MaxLength="4">
        </asp:TextBox>
    </div>
</asp:Panel>

I also have a javascript function, that adds classes based on the validity of of the data input. Again I have removed some of the surplus code.

Here's how I build $el:

var $el = $(this).closest('.form').find('input[type="text"], input[type="checkbox"], select, textarea');

Here's the javascript function I call:

function updateInputStatus($el) {

    var controls = [];

    $el.each(function () {

        $control = $(this).closest('.input-control');

        if ($.inArray($control, controls) < 0) {
            controls.push($control);
        }
    })
}

$el is one or more input controls - textbox, dropdownlist etc. In this example lets say that TextBoxMonth and TextBoxYear are our objects, $el, and the javascript function is triggered.

What I'm trying to do is build an array of unique input-control objects. In this example PanelInputControl will be found twice, however I only want it to be added to the array once.

Whats actually happening is that the code $.inArray($control, controls) < 0 always returns -1 whatever the situation (in order words its not being found in the array), and I don't understand why.

I've also tried adding this code at the end, var cleanArray = $.unique(controls);, but again the duplicates remain in the array.

I'm confused - any advice?

4

1 回答 1

3

在每次循环迭代中,您都会创建一个新的 jQuery 对象:

$control = $(this).closest('.input-control');

正是这些 jQuery 对象将您.push()放入您的controls数组中。尽管其中一些 jQuery 对象可能包含对相同 DOM 元素的引用,但您要比较的$.inArray()是 jQuery 对象,它们都是不同的对象,因此不重复。

但是,该.closest()方法本身不会返回重复项,因此您可以这样做:

controls = $el.closest('input-control');

那么你的controls变量将是一个 jQuery 对象,它只input-control包含与$el.

如果你特别想要controls一个 jQuery 对象数组,每个对象只包含一个input-control元素,但没有重复,你可以这样做:

controls = $.map($el.closest('input-control'), function(v,i) { return $(v); });
于 2013-08-03T15:31:07.437 回答