具有相似 id 模式的按钮的单个 onclick 函数 - JavaScript



我想减少代码。

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.

单击"dealsButton_*"图案化 id 元素的单个函数。我该怎么做。元素是动态加载的。

您可以使用querySelectorAll选择器[id^=dealsButton_]在一行中添加事件侦听器- 请参阅下面的演示:

function one() {
console.log("hai");
}
Array.prototype.forEach.call(
document.querySelectorAll('[id^=dealsButton_]'), function(e) {
e.addEventListener('click', one);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>

如果标记是动态加载的,则可以将其基于静态元素,如下所示:

function one() {
console.log("hai");
}
document.addEventListener('click', function(e) {
if (e.target && /^dealsButton_/.test(e.target.id))
one();
})
// dynamically add
document.body.innerHTML = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;

您是否正在寻找这样的东西:

function onClick(){
//single handler
}
$('[id*="dealsbutton_"]').click(onClick)

这是一个解决方案,您可以在没有特定名称模式的情况下根据需要选择 ID 名称。

<html>
<body>
<div id="abc">one</div>
<div id="def">two</div>
<script type="text/javascript">
function one() {
console.log("hai");
}
function addOnclickFunc (func, idArray){
idArray.forEach(function(element) {
document.getElementById(element).onclick = func;
})
}
addOnclickFunc(one,["abc","def"])
</script>
</body>
</html>

你使用jQuery和正则表达式

$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
//code here
})
});

如果要使函数动态调用名称。 将其作为数据属性传递给按钮元素并使用 eval 函数调用它

<button id="dealButton_1" data-click="one"></button>
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
var function_call = $(this).attr('data-click')
eval(function_call)
})
});

最新更新