简体   繁体   English

javascript按钮onclick按下仅起作用一次

[英]javascript button onclick press only works once

I am quite new to Javascript, and have the following question: 我是Java的新手,有以下问题:

HTML: HTML:

<div id="button"></div>

JS: JS:

for (var items in $scope.data.users){
    if ($scope.data.users.hasOwnProperty(items)) {
        document.getElementById("button").innerHTML += "<button onclick='console.log(5)'>"+items+"</button>";
        console.log(items);
    }
}

So far it works that all users in my json object are read and a button is created for each item, and when I click on a button, it shows the correct test "5" in the console. 到目前为止,它的工作原理是读取json对象中的所有用户,并为每个项目创建一个按钮,当我单击按钮时,它将在控制台中显示正确的测试“ 5”。 However, when I repeat the click, there comes an error, and I do not know why... 但是,当我重复单击时,会出现错误,并且我不知道为什么...

I think your array, or the scope, is changed on the click event. 我认为您的数组或作用域在click事件上已更改。

Although the following example is not written with (what I believe) your Angular modules, it does work and iterates over a list, creating buttons and nót throwing any errors or exceptions. 尽管以下示例未使用(我相信)您的Angular模块编写,但它确实可以工作并在列表上进行迭代,创建按钮,并且不会引发任何错误或异常。 Basically it is the same code with a different array. 基本上,相同的代码具有不同的数组。 Try to find the difference between this and your own code. 尝试找出此代码与您自己的代码之间的区别。

The only thing I changed, is making $scope.data.users an array of integers. 我唯一更改的是使$scope.data.users为整数数组。

 let arr = [1, 2, 3]; for (var items in arr){ if (arr.hasOwnProperty(items)) { document.getElementById("button").innerHTML += "<button onclick='console.log(5)'>"+items+"</button>"; console.log(items); } } 
 <div id="button"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM