2011-05-27 91 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