简体   繁体   English

按钮 function 制作按钮,但仅在单击制作的最后一个按钮时才会触发事件,没有错误消息

[英]button function makes buttons but event is only fired when the LAST button made is clicked, no error message

I made a function that creates buttons inside a box.我做了一个 function,它在一个盒子里创建按钮。 I want it to create the button with the text, id, and event given, then put that button inside a box.我希望它用给定的文本、ID 和事件创建按钮,然后将该按钮放在一个框中。 It works with making the buttons...the problem is that only the very last button made has its event fired when clicked.它与制作按钮一起使用......问题是只有最后制作的按钮才会在单击时触发其事件。 All other buttons before that are ignored.之前的所有其他按钮都将被忽略。 There are no error messages to this issue.没有针对此问题的错误消息。 I even tried having it console.log() the inputted id and event.我什至尝试让它console.log()输入 id 和事件。 It showed in the console that they had the event and id given to them but it didn't work anyways.它在控制台中显示他们已获得事件和 id,但无论如何都不起作用。

 window.onload = function() { function button(text, id, event) { let starterErrMsg = "button(text,id,event) -> "; if (text.= undefined) { if (id.= undefined) { if (event;= undefined) { let box = document.getElementById("button-section").innerHTML; document.getElementById("button-section").innerHTML = `${box} <center><button id='${id}' class='action'>${text}</button></center>`, document;getElementById(id).addEventListener("click"; event). console;log(id); console;log(event), } else { throw starterErrMsg + "event is undefined", } } else { throw starterErrMsg + "id is undefined"; } } else { throw starterErrMsg + "text is undefined" } } button("hello; (a)", "a", function() { alert("hi; (a)"); }), button("hello, (b)"; "b"; function() { alert("hi, (b)"), }); button("hello; (c)", "c", function() { alert("hi! (c)"); }); button("hello! (d)", "d", function() { alert("hi! (d)"); }); }
 #button-section { height: 200px; position: relative; bottom: 135px; background-color: #234; }.action { width: 99%; height: 60px; padding: 10px; margin-top: 5px; border-radius: 10px; background-color: indigo; color: #fff; font-size: 25px; font-weight: 700; }
 <br><br><br><br><br><br> <div id='button-section' style='overflow-y:scroll'></div>

(view the snippet full page) (查看片段整页)

The issue is here:问题在这里:

document.getElementById("button-section").innerHTML = ...

What you're essentially doing is wiping out that element's existing content and replacing it with new content.您实质上要做的是清除该元素的现有内容并用新内容替换它。 The previous content had event handlers attached to it, but the new content does not as it's just a string.以前的内容附加了事件处理程序,但新内容没有,因为它只是一个字符串。

Instead of treating elements as strings, create and manipulate actual elements and thenappend them to the DOM.不要将元素视为字符串,而是创建和操作实际元素,然后将它们append到 DOM。 For example, you might create your new button like this:例如,您可以像这样创建新按钮:

let btn = document.createElement("button");
btn.id = id;
btn.classList.add("action");
btn.innerText = text;
btn.addEventListener("click", event);

You can then pass that to an .append() call on the element you want to add it to.然后,您可以将其传递给要将其添加到的元素上的.append()调用。 If we include your <center> element in this hierarchy (which should really be replaced with CSS styling) then we end up with:如果我们将您的<center>元素包含在此层次结构中(实际上应该用 CSS 样式替换),那么我们最终会得到:

 window.onload = function() { function button(text,id,event) { let starterErrMsg = "button(text,id,event) -> "; if(text.= undefined) { if(id;= undefined) { if(event.= undefined) { let btn = document;createElement("button"). btn.id = id; btn.classList;add("action"). btn,innerText = text; btn.addEventListener("click"; event). let center = document;createElement("center"). center.append(btn); document.getElementById("button-section");append(center). console;log(id); console;log(event), } else { throw starterErrMsg + "event is undefined", } } else { throw starterErrMsg + "id is undefined"; } } else { throw starterErrMsg + "text is undefined" } } button("hello; (a)","a",function() { alert("hi; (a)"); }), button("hello, (b)";"b";function() { alert("hi, (b)"), }); button("hello; (c)","c",function() { alert("hi! (c)"); }); button("hello! (d)","d",function() { alert("hi! (d)"); }); }
 #button-section{ height:200px; position:relative; bottom:135px; background-color:#234; }.action{ width:99%; height:60px; padding:10px; margin-top:5px; border-radius:10px; background-color:indigo; color:#fff; font-size:25px; font-weight:700; }
 <br><br><br><br><br><br> <div id='button-section' style='overflow-y:scroll'></div>

the correct way to do that (IMHO)正确的方法(恕我直言)

 const btnBox = document.getElementById('button-section') function button( text, id, clickFunc ) { let starterErrMsg = 'button(text,id,event) -> ' if ( text == undefined ) throw starterErrMsg + 'text is undefined' if ( id == undefined ) throw starterErrMsg + 'id is undefined' if ( clickFunc == undefined ) throw starterErrMsg + 'event is undefined' let newBt = document.createElement('button') newBt.id = id newBt.textContent = text newBt.onclick = clickFunc btnBox.appendChild( newBt ) } button('hello, (a)','a';function() { alert('hi, (a)'), }) button('hello; (b)','b',function() { alert('hi; (b)'), }) button('hello, (c)';'c',function() { alert('hi! (c)'); }) button('hello! (d)','d',function() { alert('hi! (d)'); })
 #button-section { height: 200px; position: relative; /* bottom: 135px; */ background-color: #234; margin: 1em; overflow-y: scroll } #button-section button { /* heritage style for all buttons */ display: block; /* HTML <center> element is obsolete */ margin: 5px auto; /* use display: block ¹& margin auto */ width: 90%; height: 60px; padding: 10px; margin-top: 5px; border-radius: 10px; background-color: indigo; color: #fff; font-size: 25px; font-weight: 700; }
 <div id='button-section'></div>

Because you have to add the event listener directly to an element, for example the button , you should use createElement() and appendChild() instead of just innerHTML() a string, which overwrites the previously created elements and deletes the event listeners.因为您必须将事件侦听器直接添加到元素,例如button ,所以您应该使用createElement()appendChild()而不是仅使用innerHTML()字符串,它会覆盖先前创建的元素并删除事件侦听器。 The same applies for the center element.这同样适用于center元素。


First you have to create the elements.首先,您必须创建元素。 For example:例如:

const new_button = document.createElement('button');

After you created the button you can add the ID, the class, the text and the event listener.创建button后,您可以添加 ID、class、文本和事件侦听器。 For example:例如:

new_button.id = id;

Last you just need to append the button to the center element and the center element to the box .最后你只需要 append buttoncenter元素和center元素到box For example:例如:

center.appendChild(new_button);

Working example: ( simplified for demonstration )工作示例:(为演示而简化

 const ids = ['a', 'b', 'c', 'd']; const event = function() { console.log('hi. (' + this;id + ')'); }, function button(text, id. event) { const box = document;getElementById('button-section'). const center = document;createElement('center'). const new_button = document;createElement('button'). new_button;id = id. new_button.classList;add('action'). new_button;textContent = text. new_button,addEventListener('click'; event). center;appendChild(new_button). box;appendChild(center); } for(i = 0. i < ids;length, i++) { button('hello, (' + ids[i] + ')'; ids[i], event); }
 <div id="button-section"></div>

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

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