我在onClick事件javascript函数中的ID有问题

时间:2019-01-20 20:27:54

标签: javascript

我正在尝试制作一些空闲的单击游戏,但是我的startIdle函数有问题。 我无法将ID传递到开始计数所需的输入进度条。 我有一个输入字段和一个来自obj的foreach id按钮。

function addRow(id) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML =
    '<div class="w3-blue" name="idle" id="'+id+'" style="height:24px;width:20%"></div>\
     <button onclick="startIdle('+id+')">Click me</button>';
document.getElementById('content').appendChild(div);
}

function startIdle(id) {
_counter = 1;
_timer = setInterval(function(){
    document.getElementById(id).style.width = (_counter + "%");
    _counter++;
    if(_counter > 100) clearInterval(_timer);
}, 100);
}

function createIdles(){
for (var key in money) {
    // skip loop if the property is from prototype
    if (!money.hasOwnProperty(key)) continue;
    var obj = money[key].id;
    addRow(obj)
}
}
createIdles()

这是我得到的console.log 未捕获的ReferenceError:在HTMLButtonElement.onclick上未定义startIdle

2 个答案:

答案 0 :(得分:0)

我删除了onclick属性,并分别执行绑定。绑定和元素查找在setTimeout内部完成,以确保在代码运行时DOM中存在元素。

// Note: I'm using a data-id attribute on the <button> so as to not 
// duplicate the id on the <div class="w-3">

function addRow(id) {
  var div = document.createElement('div');
  div.className = 'row';
  div.innerHTML =
    '<div class="w3-blue" name="idle" id="' + id + '" style="height:24px;width:20%"></div>\
     <button data-id="' + id + '">Click me</button>';
  document.getElementById('content').appendChild(div);
}

function startIdle() {
  // Remember the data-id attribute from above?
  alert('clicked ' + this.getAttribute('data-id'));
}

for (var i = 0; i < 5; i++) {
  addRow(i);
}

// Bind click events in separate event loop to ensure elements are present in DOM
setTimeout(function() {
  var els = document.querySelectorAll("button[data-id]");

  els.forEach(function(el) {
    el.addEventListener("click", startIdle);
  })
});
<div id="content"></div>

http://jsfiddle.net/4mr02ktu/2/

答案 1 :(得分:0)

您的问题是,在范围内定义了startIdle。将其移出document.ready。除非您可以从控制台调用该函数,否则该函数将无法全局使用。

或者,以Andy Hoffmans解决方案为基础,以编程方式将onClick绑定到文档范围内。例如,

document.querySelectorAll('button[data-id]')
   .forEach(elm => elm.addEventListener('click', 
     () => startIdle(elm.dataset.id)))

您可能可以使用jquery进行一些改进。