如何解决检索子输入类型时出现问题当前返回为\'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/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。