onclick不触发函数(通过innerHTML创建的按钮)

时间:2017-05-04 10:24:29

标签: javascript html

首先我尝试了:

   document.getElementById(trade_selection[i].slug).onclick = send_trade_request(auction_a, slug_for_trading, username);

但它在任何点击事件发生之前触发了该函数,所以我发现我需要调用匿名函数才能使它工作,所以我试过了:

var slug_for_trading = 'slug for trading';
var trade_selection = [{
  name: 'foo',
  slug: 'niceslug',
  selling__username: 'foo',
  price: 123
}, {
  name: 'foo1',
  slug: 'veryveryniceslug',
  selling__username: 'foo1',
  price: 123
}];

var el = document.getElementById('test');
el.innerHTML = "TRADE <br>";
for (var i = 0; i < trade_selection.length; i++) {
  var username = trade_selection[i].user_selling__username;
  var auction_a = "<a href='http://example.com/foo/" + trade_selection[i].slug + "'>" + trade_selection[i].name + "</a>";
  var trade_request_button = "<button id='" + trade_selection[i].slug + "'>Send Trade Request</button>";
  el.innerHTML = el.innerHTML + "- Auction name: " + auction_a + " | Price: " + trade_selection[i].price + trade_request_button + "<br>";
  console.log(document.getElementById(trade_selection[i].slug));
  document.getElementById(trade_selection[i].slug).onclick=function(){
  send_trade_request(auction_a, slug_for_trading, username);
  }
}

function send_trade_request(auction_a, auction_b, to) {
  alert(auction_a + " " + auction_b + " " + to);
}
<div id='test'>

</div>

并且它有效,除了第一个按钮根本不调用该功能。我似乎无法弄清楚为什么会这样。寻找一些方向。

2 个答案:

答案 0 :(得分:3)

好的问题是,你正在使用&#34; innerHTML&#34;将新元素分配给&#34; root&#34; DIV。通过说el.innerHTML = el.innerHTML +&#34;新元素HTML&#34;。你正在删除&#39;以前添加的事件监听器。

改为使用:

  var button = document.createElement('button');
  button.innerHTML = "send request: " + i;
  button.id = trade_selection[i].slug;
  el.appendChild(button);

这样,您可以保留以前的DOM树并附加新元素。经过测试并且有效。

答案 1 :(得分:1)

问题是您实际上是在立即调用send_trade_request(auction_a, slug_for_trading, username);

你应该在一个函数中包装send_trade_request(),并且引用该函数而不实际调用它

function myEvent(){ 
    send_trade_request(auction_a, slug_for_trading, username); 
};

document.getElementById(trade_selection[i].slug).onclick = myEvent;