How to check if an element is an array or single

jQuery 1.7.1

Sometimes I have an element as an array,

<tr><td><input type="hidden" class="p" name="it" value="1"/></td></tr>
<tr><td><input type="hidden" class="p" name="it" value="2"/></td></tr>

The below jQuery code works,

$(".p").each(function(i){
alert($('.p')[i].value);
});

Sometime I have that element as a single element

<tr><td><input type="hidden" class="p" name="it" value="1"/></td></tr>

I want to make sure if the hidden input is an array or a single element before trying to execute the above jQuery code. How can I do that using jQuery?


Actually, that code works fine for both one input and two inputs.

But, use the size method to check:

if ($(".p").size() > 1) {
    $(".p").each(function(i){
        alert($(this).value);
    });
}

You could check the length of the set jQuery returns.

var p = $('.p');
if ( p.length == 1 )
    // single
else if ( p.length > 1 )
    // set

But this, I believe, is not your problem. Your jQuery code should not reload $('.p') on each iteration. Try this — it'll work with one or multiple matched elements:

$(".p").each(function(){
    alert(this.value);
});

The result of a DOM query is always a jQuery object. It cannot be a single element. $(".p").length will tell you the number of elements in the returned object, which can be 0 if the query matched no objects.

链接地址: http://www.djcxy.com/p/19314.html

上一篇: 如何处理胡须模板中的字符串或字符串数​​组

下一篇: 如何检查一个元素是一个数组还是单个元素