【问题标题】:Jquery Each Input Within DIV (Has A Table)Jquery DIV 中的每个输入(有一个表)
【发布时间】:2012-07-18 12:38:09
【问题描述】:

我目前正在尝试从 DIV 中获取所有输入元素。

$("[required]").each(function() {

});

我有这段代码,它返回带有required 属性的每个元素。

我知道在 each() 的功能内我可以使用每个项目,例如:

$(this)

所以我得到了如下所示的 div ID,并尝试通过以下方式从中获取所有输入:

var id = $(this).attr('id');
console.log("### " + id);
console.log($("#" + id + " > :input").length);

当我在该 DIV 中有 4 个放入元素时返回 0(在 div 中也有一个表)。

我最理想的做法是为 div 中的每个输入元素打印其 ID。

更新

<div id="contactAddress" required="true">

 <td>Addres line 1:</td>
 <td colspan="2">
 <input type="text"/>
 </td>
 <td>Addres line 2:</td>
 <td colspan="2">
 <input type="text" />
 </td>
 </tr>
</div>

console.log($(this).html());

不显示任何内容,但如果我在下面添加任何内容或类似...

 <div id="contactAddress" required="true">
 <input type="text" />

然后运行console.log($(this).html());它显示它没有放在桌子上?

我使用 Jquery Mobile 的任何想法

【问题讨论】:

  • 你有没有类似的东西 $("#parent-id input[type=text]").each(function(){ }); ?

标签: javascript jquery html input foreach


【解决方案1】:

下面会找到 div 元素内的所有输入。然后它会留下这个元素的 id 的日志。

$("div > input").each(function() {
  console.log( $(this).attr("id") );
});

如果您需要包含输入的 div id,您可以使用 .parent()

$("input").each(function() {
  console.log( $(this).parent().attr("id") );
});

【讨论】:

  • 是的,但对于 div ID 或 this(作为 div 元素)
  • $(this) 指的是每个输入,因为它通过每个输入。您需要 div 的 id 吗?
  • var id = $(element).attr('id'); $("#" + id + " > 输入")
猜你喜欢
  • 2011-05-15
  • 2012-07-08
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多