2012-02-23 78 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

相關問題