2013-05-31 58 views
0

輸入傳遞到JavaScript變量屬性從HTML輸入ID =「屬性」

<input type="text" value="" id="row1"> 
<input type="text" value="" id="row2"> 

需要從行獲得最後一個字符,並把它傳遞給JavaScript變量。這裏是ROW1和ROW2,需要得到變量1和2

我嘗試使用這個,但不工作

$('[id^="row"]').each(function (index, row) { 
var row = row.id.substring(3); 
alert (row);//this is only to check if value exists (alert or not) 
}); 

沒有戒備的。但需要:第一次迭代(.each)var行是1,第二個, - 2等。

以此爲例。這個例子的作品,但我的代碼不

$.each([52, 97], function(index, value) { 
alert(index + ': ' + value); 
}); 
+1

你使用jQuery?你的代碼似乎,但你沒有提及它,並沒有使用'jquery'標籤... –

+2

代碼是正確的。很可能它不在文檔就緒處理程序中,並且它在實際的HTML –

+0

之前加載,我建議閱讀jQuery教程:http://learn.jquery.com/about-jquery/how-jquery-works/。它解釋瞭如何正確設置你的代碼。 –

回答

1

你的代碼工作正常,提供是:

  1. 你實際上是包括jQuery的在某些時候(你沒有提到它在你的問題,但您似乎正在使用它)

  2. 您運行代碼之後存在該元素

下面是包含與jQuery你的代碼,我們確保代碼不會運行,直到元素後存在:Live Copy | Live Source

<!DOCTYPE html> 
<html> 
<head> 
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
</head> 
<body> 
    <input type="text" value="" id="row1"> 
    <input type="text" value="" id="row2"> 
    <script> 
    (function($) { 
     $('[id^="row"]').each(function (index, row) { 
     var row = row.id.substring(3); 
     alert (row);//this is only to check if value exists (alert or not) 
     }); 
    })(jQuery); 
    </script> 
</body> 
</html> 

注意script標籤是如何其所操作的元素,使腳本運行時,它們的存在。

工作:

<script> 
    (function($) { 
     $('[id^="row"]').each(function (index, row) { 
     var row = row.id.substring(3); 
     alert (row);//this is only to check if value exists (alert or not) 
     }); 
    })(jQuery); 
    </script> 
    <input type="text" value="" id="row1"> 
    <input type="text" value="" id="row2"> 

...因爲腳本運行時,元素還不存在。

如果由於某種原因您無法控制script元素的位置,則可以使用jQuery的ready函數等待直到加載DOM爲止運行您的代碼。但是,如果您控制script標籤的去向,則無需這樣做,只需在關閉</body>標籤之前將它們放在文檔的末尾即可。

更多:

+0

謝謝,你的代碼有效。我將與我的代碼進行比較(瞭解)。 – user2360838

+0

@ user2360838:主要的是確保腳本在元素存在之後才運行。我已經添加了一個反例來演示。最好, –

+0

啊,我忘了包括jquery-1.9.1.min.js .... – user2360838