添加事件监听器javascript按钮

时间:2016-06-24 07:44:24

标签: javascript

检查JSfiddle:https://jsfiddle.net/a7a0fa3g/ 我有以下代码:

var z = 1;
function myFunction() {
  var x = document.getElementById("inptext").value;
  var y = document.getElementById("inpadress").value;
  document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML  + '<tr><td>' + x + '</td><td>' + y + '</td></tr>';
  var h = '<button style="margin-left:8px" class="edit" id=vda' + z + '>Edit</button>';
  var w = '<button style="margin-left:4px" class="deleteit" id=a' + z + '>Remove</button>';
  var f = '<div id=zzza'+z+' style=height:10px></div>';
  z =  z + 1;
  var total = h + w + f ;
  document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + total;
}

我尝试在z = z + 1之前添加以下代码:

var id = 'vda'+z;


document.getElementById(id).addEventListener('click', doSomething, false);

还:

function doSomething() {
   alert('Button clicked');
}

但它完全不起作用。

1 个答案:

答案 0 :(得分:0)

当select元素为null(html中不存在)时,

addEventListerner不起作用,因此在addEventListerner之前首先添加你的button元素。

var z = 1;
myFunction();
function myFunction() {
  var x = document.getElementById("inptext").value;
  var y = document.getElementById("inpadress").value;
  document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML  + '<tr><td>' + x + '</td><td>' + y + '</td></tr>';
  var h = '<button style="margin-left:8px" class="edit" id="vda'+z+'">Edit</button>';
  var w = '<button style="margin-left:4px" class="deleteit" id="a' + z +'">Remove</button>';
  var f = '<div id=zzza'+z+' style=height:10px></div>';
  //add button first before event attach
  var total = h + w + f ;
  document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + total;
  var id = 'vda'+z;
  document.getElementById(id).addEventListener('click', doSomething, false);
  z =  z + 1; 
}

注意 你需要&#34;&#34;用js var分配id时

不正确
var h = '<button style="margin-left:8px" class="edit" id=vda' + z + '>Edit</button>';

正确

var h = '<button style="margin-left:8px" class="edit" id="vda' + z + '">Edit</button>';