我用js创建了一个div(var div = document.createElement("div");)。现在我想在创建 div 后插入一个 onclick 函数。由于某种原因,当我仅单击游戏场时,就会触发 onclick 函数。
var create_divs = function(check_if_right_div){
var random_class = Math.floor((Math.random() * 5) + 1);
var id = div_id += 1;
var random_position = 0 + 100*Math.floor(Math.random()*6);
var div = document.createElement("div");
div_id_selection.push('div' + id);
div.className = 'class'+random_class;
div.id = 'div' + id;
div.style.left = random_position;
div.addEventListener("click",check_if_right_div(div));//the function is triggered when I click the playfield, which is a big div that contains the other divs
document.getElementById('play_field').appendChild(div);
var check_if_right_div = function(div_to_check){
var div_class =div_to_check.className;
console.log(div_class);
};
最佳答案
你需要这样做
div.onclick = function(){
check_if_right_div(div);
};
当你执行这个 check_if_right_div(div) 时,它是函数执行,这意味着通过使这个 div.addEventListener("click",check_if_right_div(div));您执行函数 check_if_right_div(div)
关于javascript - 使用 onclick-function 创建 div(纯 Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43400701/