如何在一个函数中增加JavaScript getElementById变量

How to increment JavaScript getElementById variable inside one function?

本文关键字:函数 增加 JavaScript 变量 getElementById 一个      更新时间:2023-09-26

我需要在用户单击按钮时有效的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>