single onclick function for buttons with a similar id pattern - JavaScript
问题 I want to reduce the code. function one() { console.log("hai"); } document.getElementById('dealsButton_1').onclick = one; document.getElementById('dealsButton_2').onclick = one; //I want the above 2 lines of code reduced to one. A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded . 回答1: You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below: