繁体   English   中英

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

[英]i have a problem with a id in onClick event javascript function

我正在尝试制作一些空闲的单击游戏,但是我的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我得到了Uncaught ReferenceError:在HTMLButtonElement.onclick中未定义startIdle

我删除了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/

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

或者,基于Andy Hoffmans解决方案,以编程方式在document.ready范围内绑定onClick,例如

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

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

暂无
暂无

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

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