[英]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);
});
您的代码可以正常运行, 但前提是:
您实际上在某个时候包括了jQuery(您在问题中没有提到它,但您似乎正在使用它)
您在元素存在之后运行代码。
这是您的包含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.