簡體   English   中英

從html輸入id =“ attribute”傳遞給javascript變量屬性

[英]Pass to javascript variable attribute from html input id=“attribute”

輸入項

<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(您在問題中沒有提到它,但您似乎正在使用它)

  2. 您在元素存在之后運行代碼。

這是您的包含jQuery的代碼,並且我們確保在元素存在后該代碼才能運行: Live Copy | 現場直播

<!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>標記的前面。

更多:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM