1

我似乎无法在 jQuery 1.6 中获得 type 属性

<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="checked" />
</div>

和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 = '';
    }*/
});

看我的小提琴

4

4 回答 4

2

这是因为您误解了$.each()接受数组或对象(而不是选择器)的函数。当您将字符串传递给 时$.each(),jQuery 会遍历字符串中的所有字符(在大多数浏览器中)。

要解决此问题,您可以将选择器传递给 jQuery 并使用结果$.each(),或调用.each()结果:

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

查看您更新的小提琴

如果你觉得大胆,你可以在函数内部抛弃 jQuery 并直接访问属性,提高效率并减少代码:

var input_type = this.type;
于 2011-06-03T17:46:45.913 回答
1

即使 Andy E 对$.each, 使用attr()type更有意义,因为它prop()应该只用于布尔类型属性:

$('#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 = '';
    }*/
});
于 2011-06-03T17:45:23.000 回答
0

您应该使用以下内容来获取属性值

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

于 2011-06-03T17:45:25.730 回答
0

type 是属性而不是属性,请参见此处:

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

于 2011-06-03T17:48:07.833 回答