【问题标题】:How to increment JavaScript getElementById variable inside one function?如何在一个函数中增加 JavaScript getElementById 变量?
【发布时间】:2014-04-01 03:51:42
【问题描述】:

我需要增加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>

例如:当 index 为 2 且 var c 从 div 中获取数字 3 时,下面的 textarea 名称应该是 -> txt24, txt25, txt26, etc...

【问题讨论】:

  • 使用count = parseInt(count),而不是parseInt(count);
  • 它并没有解决我递增的问题:(

标签: javascript html dom


【解决方案1】:

让我们使用“字典”来存储每个父元素的计数,并将其保留在 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);
}

【讨论】:

  • 我根据你的建议改变了这个,但它只解决了整数问题。它仍然不会增加。问题是即使我将计数变量更改为数字 - 例如 12。每次单击按钮时它都会给我数字 13。而不是 13、14、15...
  • A 字段实际上是 div id 看起来像这样:id="A1", id="A2" 等等...而且这些 div 里面不时有不同的数字。
  • @user3244442:啊,我明白了。我正在根据我的想法更新我的答案。
【解决方案2】:

您可以将数据保存在任何变量中,例如按钮本身 :-)

<!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>

【讨论】:

    猜你喜欢
    • 2021-07-08
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多