检索子输入类型时出现问题当前返回为\'undefined\'

问题描述

| 因此,让您了解我想要达到的目标的最佳方法是查看此演示: 现场演示。 问题在于返回的类型是\'undefined \',而不是\'text \'。 有人可以解释为什么会这样吗? 非常感谢,     

解决方法

        如果您不想更改HTML,则此代码有效:
$(\".question\").each(function(){
        var type = $(\'input[type != \"hidden\"]\',this).attr(\"type\");
        alert(type);
});

// Or

$(\".question\").each(function(){
        var type = $(this).find(\'input[type != \"hidden\"]\').attr(\"type\");
        alert(type);
});
    ,        考虑一下您的代码在做什么:
// for each \'.question\' element
$(\".question\").each(function() { 
    // find the \'input\' children which are not \'type=hidden\'
    var children = $(this).children(\'input[type != \"hidden\"]\');
    // get the type
    var type = children.attr(\'type\');
}
您有两个
question
元素。第一个不包含与子代选择器匹配的元素(
text
输入不是直接子代,因为它嵌套在
h3
中),因此您有一个空数组。 在
each
的第一次迭代中,您尝试从一个空数组中读取
attr(\'type\')
,这将为您提供
undefined
。 在
each
的第二次迭代中,您尝试从具有多个元素的数组中读取
attr(\'type\')
。 我认为您正在尝试做的事情更多...
$(\".question\").each(function(){
    $(this).find(\'input[type != \"hidden\"]\').each(function() {
         alert($(this).attr(\"type\"));
    });   
});
请注意,
find
贯穿所有孩子,而不仅仅是
children
直属孩子。     ,        问题在于,您尝试在\ .question \ div中找到一个非隐藏的输入元素-child。 但是您的函数不会拾取孙元素,在这种情况下就是那个。这就是为什么您返回“未定义”响应的原因。     ,        这是因为输入
type=text
h3
内:
<h3>The binary language consists of <input type=\'text\' name=\'response[4][answer]\'>digit(s).</h3>
将HTML修复为:
<h3>The binary language consists of </h3><input type=\'text\' name=\'response[4][answer]\'>digit(s).
小提琴:http://jsfiddle.net/maniator/Z6jDR/12/