开发者

jQuery 1.6 type property is undefined

I can't seem to get the type property in jQuery 1.6

<div id="div_id">
    <input type="text" value="foo" />
    <input type="text" value="foo" />
    <input type="text" value="foo" />
    <input type="text" value="foo" />
    <input type="checkbox" checked="ch开发者_C百科ecked" />
</div>

and jquery

$.each('#div_id input',function(index,value){
    var input_type = $(this).prop('type')
    alert(input_type);
    /*
    switch(input_type) {
         case 'checkbox':
            $(this).prop('checked',false);
            break;
                //more cases here
        default:
        this.value = '';
    }*/
});

see my fiddle


This is because you've misunderstood the $.each() function, which accepts an array or object (as opposed to a selector). When you pass a string to $.each(), jQuery iterates over all the characters in the string (in most browsers).

To fix the issue you can pass the selector to jQuery and either use the result in $.each(), or call .each() on the result:

$('#div_id input').each(function(index,value){
    var input_type = $(this).prop('type');
    /* ... */
});

See your updated fiddle.

If you're feeling bold, you can ditch jQuery inside the function and access the property directly, increasing efficiency and reducing code:

var input_type = this.type;


Even though Andy E is right about the $.each, it makes more sense to use attr() for type, as prop() should only be used for boolean type attributes:

$('#div_id input').each(function() {
    var input_type = $(this).attr('type');
    alert(input_type);
    /*
    switch(input_type) {
         case 'checkbox':
            $(this).prop('checked',false);
            break;
                //more cases here
        default:
        this.value = '';
    }*/
});


You should use the following to get attributes values

$(this).attr("type");


type is an attribute not a property, see here:

http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜