2011-05-27 136 views
2

基本上我有几个div,每个包含一个问题。这个问题可以用单个输入,单选按钮或复选框来呈现。如何识别儿童输入类型

我想确定输入类型是什么,当通过div循环。

下面的代码实现这个不起作用,只是试图展示我想要实现的。

$(".question").each(function(){ 

     var type = $(this).children('input').attr("type").val(); 
     alert(type); 
}); 
+0

定义 “不工作” 它抛出一个错误?它做什么? 我不认为你需要.val()的attr – Patricia 2011-05-27 14:04:15

+0

以及没有什么。我假设,因为我没有办法缩小到一个特定的输入 – buymypies 2011-05-27 14:06:40

回答

1

卸下VAL():

var type = $(this).children('input').attr("type"); 

例如

$(document).ready(function(){ 
     $('button').click(function(){$(".question").each(function(){ 

     var type = $(this).children('input').attr("type"); 
     alert(type); 
     }); 
     }); 
    }); 


<div class="question"> 
    <input type="radio">hello</input> 
</div> 

<div class="question"> 
    <input type="checkbox">hello</input> 
</div> 

<div class="question"> 
    <input type='text' name='response[4][answer]'></input> 
</div> 

<button>Click</button> 
+0

感谢BonyT,这工作,但是当div包含一个简单的文本输入,输出是'未定义'。为什么会这样? – buymypies 2011-05-27 14:12:17

+0

你还没有设置“文本”的类型? – BonyT 2011-05-27 14:16:47

+0

肯定有。 – buymypies 2011-05-27 14:23:42

1

Live Demo

$(".question > input").each(function(){ 
     var type = $(this).attr("type"); 
     alert(type); 
}); 
+0

这很好,如果我想循环每个div中的每个输入,但我不知道。我只是想循环每个div,并且基本评估是否没有响应。感谢寿。 – buymypies 2011-05-27 14:05:39

0

这应该让你去:

$('div').each(function(){ 
    $(this).children('input').each(function(){ 
     alert($(this).attr('type')); 
    }); 
}); 

小提琴:http://jsfiddle.net/p6F9T/

1

var type = $(this).find("input").get(0).type;

+1

感谢这个工程,即使输入是在儿童的内部 – Geomorillo 2013-09-12 14:15:24