html按钮的动态onclick调用

Dynamic onclick call of html buttons

本文关键字:onclick 调用 动态 按钮 html      更新时间:2023-09-26

在我的javascript中,我有一个由3个元素组成的数组:

var array = ["one", "two", "three"]; 

如何创建3个html按钮,使每个按钮的onclick调用一个带有参数array[I]的函数。

对于我想要的结果:

<button onclick='function("one")'></button>
<button onclick='function("two")'></button>
<button onclick='function("three")'></button>

使用内联处理程序有时会给我们带来麻烦。例如,通过在事件处理程序中使用this访问当前元素。在这种情况下,可以使用datasetaddEventListener

var array = ["one", "two", "three"];
array.forEach(function(itm){
  var elem = document.createElement("button");
  elem.textContent = itm;
  elem.dataset.data = itm;
  elem.addEventListener("click", clickHandle, false);
  document.body.appendChild(elem);
});
function clickHandle(){
  alert(this.dataset.data); //will display "one"/"two"/"three" based on the element clicked.
}

演示

为了让您快速运行,这里有一个对现有代码的快速修复。

如果你说按钮会按顺序排列,那么你可以利用按钮的索引。

var array = ["one", "two", "three"]; 
function Myfunction(e){
  var index = $('.container button').index(e.target)
  alert(array[index]);  // now you have the value here, use it for your further stuff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button onclick='Myfunction(event)'></button>
<button onclick='Myfunction(event)'></button>
<button onclick='Myfunction(event)'></button>
  </div>


如果您正在寻找一种更干净的方法,那么我建议不要使用onclick属性来绑定事件,而是使用Jquery直接绑定事件。如下图所示。。

var array = ["one", "two", "three"];
$('.container button').on('click', function() {
  var index = $('.container button').index($(this));
  alert(array[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button ></button>
  <button ></button>
  <button ></button>
</div>

var btn_list;   //The buttons parent element
var your_func;  //callback function
for (var i = 0; i < array.length; i++)
{
    btn = document.createElement('BUTTON'); //create element
    btn.onclick = function() //assign callback, with item
    {
        your_func(array[i]);
    };
    btn_list.appendChild(btn); //and add it to parent element
}

当然,您的回调函数和buttons父元素是在…之前定义的。。。。