如何在一个函数中增加JavaScript getElementById变量
How to increment JavaScript getElementById variable inside one function?
我需要在用户单击按钮时有效的add function
中增加我的变量计数。我知道如果我以某种方式在此函数之外声明var count
,然后放置count++
以便每次用户单击按钮时它都有新值,则可以做到这一点,但是您可以在我的代码中看到我需要在里面声明它。
因此,对于每个索引(例如:1,2,3...),var count
应该单独工作,并且仅在该函数下递增。
问题是每当用户单击按钮时,它都会返回到第一行中的var c,并且增量不起作用:(
<script type="text/javascript">
function add(index) {
var count = document.getElementById("A"+index).innerHTML;
count = parseInt(count);
count++;
var textarea = document.createElement("textarea");
textarea.name = "txt" + index + count;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
例如:当索引为 2 并且 var c 从div 获得数字 3 时,以下文本区域名称应该是 -> txt24、txt25、txt26 等......
让我们用一个"字典"来攻击这个问题,用于存储每个父元素的计数,让我们将其保留在您的add()
函数之外:
var elementCounts = {};
现在,让我们调整 add()
方法,如果该对象不存在,则在此对象中放置初始计数,如果存在,则对其进行更新。然后,您可以在后续调用中读取并递增对象中的值:
function add(index) {
// build a key based on the index
var key = 'A' + index;
// Check if the key (property) exists in our dictionary (object)
if (key in elementCounts) {
// it's there, increment the count
elementCounts[key]++;
} else {
// it's not there, let's add it and start it at 1
elementCounts[key] = 1;
}
var textarea = document.createElement("textarea");
// in this line, simply access the current count from the dictionary
textarea.name = "txt" + index + elementCounts[key];
// and the rest of the code remains the same
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner" + index).appendChild(div);
}
您可以将
数据保存在任何变量中,例如按钮本身:-)
<!DOCTYPE html>
<html lang="en">
<head>
<title> Bla! </title>
<script type='text/javascript'>
function Count(obj) {
if (! obj.data) obj.data = 0;
obj.data++;
var div = document.createElement('div');
div.id = 'id_' + obj.data;
div.innerHTML = "This is Number:" + obj.data;
document.getElementById('containerDiv').appendChild(div);
}
</script>
</head>
<body>
<button onclick='Count(this)'> Click to count </button>
<div id='containerDiv'>
</div>
</body>
</html>
相关文章:
- 如何通过ajax增加/减少PHP变量值并重新加载函数
- 函数比javascript中的步进器增加/减少更多
- javascript函数,它将数组作为输入,将每个数组元素增加1,并返回增加值的新数组
- jQuery keyup事件增加-“;函数“;将设置为0
- 角函数每秒钟增加一次
- 增加一个数字并将其附加到函数
- jquery使用单击函数增加PHP变量
- 使用点击函数增加 PHP 变量的值
- 登录以使用 jquery 滚动函数将整数变量从最小值增加到最大值
- 在函数实例中使用原型增加价值
- 函数在Javascript中不起作用(增加/减少按钮)
- 使用函数按间隔调用自身,增加变量,并设置 id 等于该变量的元素的类值
- 传递到力矩函数的日期增加1分钟
- 每次运行函数时增加一个变量
- 我的函数赢得了'Don’不要在文件中增加段落
- 循环时,增加变量在setimeout函数内部没有任何效果
- 自动增加JS函数参数和目标中附加的类或ID号
- 通过php函数增加HTML表行
- Javascript函数增加/减少cellValue
- CSS冲突与JavaScript函数增加减少字体大小