2012-02-23 83 views
0

如何将行号分配为文本框的值?将行号分配给文本框

我有以下几点。

<div id="rows"> 
    <div><input type="text"></div> 
    <div><input type="text"></div> 
    <div><input type="text"></div> 
</div> 

如何我jQuery实现这一目标?

<div id="rows"> 
    <div><input type="text" value="1"></div> 
    <div><input type="text" value="2"></div> 
    <div><input type="text" value="3"></div> 
</div> 
+0

只是要小心用'input'选择,将选择按钮以及是他们的行DIV中。 – gdoron 2012-02-23 21:37:00

回答

3

使用.each()

$("#rows input").each(function(i, elem) { 
    $(this).val(i+1); 
}); 

jsFiddle

+0

你可以使用'this.value'来创建jQuery对象来设置值。而'input'选择器不仅会选择'textboxes',还会选择按钮等。 – gdoron 2012-02-23 21:06:45

+0

他没有任何东西,只有文本框,所以为什么只通过筛选type =“text”来减慢选择器?不要过度分析:P – Interrobang 2012-02-23 21:13:13

+0

“epsilon”开销不计算在内。你永远不能确定他的HTML是完整的,而不是简单的演示。 – gdoron 2012-02-23 21:16:58

0
$("#rows input[type='text']").each(function(index) { 
    this.value = index + 1; 
}); 
+0

@downvoter !!! **评论请** – gdoron 2012-02-23 21:07:27

+1

我不知道你为什么被忽略 – 2012-02-23 21:09:25

相关问题