javascript中的事件委托

时间:2017-09-03 15:16:56

标签: javascript



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>

<body>
<div id="print_data"></div>
<input type="text" id="name" placeholder="name">
<input type="text" id="title" placeholder="title">
<input type="text" id="email" placeholder="email">
<input type="submit" id="submit" value="submit">

<script type="text/javascript">	
var submit = document.getElementById("submit");
var printdata = document.getElementById("print_data");
	

submit.onclick = function(){
var name = document.getElementById("name").value; 
var title = document.getElementById("title").value;
var email = document.getElementById("email").value;
$.ajax({
  type: 'POST',
  url: 'http://rest.learncode.academy/api/sumit/friend',
  data: {name:name, title: title, email:email},
  success: function(data) {
  }
});	
}


$.ajax({
  type: 'GET',
  url: 'http://rest.learncode.academy/api/sumit/friend',
  success: function(data) {  
	  var vals ="";
	  for(var i=0; i<data.length; i++){
		  var obj = data[i];
		  vals += '<ul><li>'+obj.name+'</li><li>'+obj.title+'</li><li>'+obj.email+'</li><li><input type="submit" class="del" value="X" id="'+obj.id+'"></li><li><input type="submit" class="edit" value="edit" id="'+obj.id+'"></li></ul>'
		  printdata.innerHTML =  vals;
	  }
  }
});	
	

 
document.addEventListener("DOMContentLoaded", function(event) { 
alert('hi');
var edit = document.getElementsByClassName("edit");	
for(var i=0; i<edit.length; i++){
edit[i].addEventListener('click', function(){
alert(this.getAttribute("id"));
})  
};		
});
			
</script>
</body>
</html>
&#13;
&#13;
&#13;

我已经通过ajax动态生成了一堆输入类型。但我的问题是我的脚本首先执行然后我的dom加载。所以它不起作用,暂时我通过setTimeout函数执行该代码。但我不想要一个真正的修复。谢谢。 示例代码如下:

&#13;
&#13;
var edit = document.getElementsByClassName("edit");	 for(var i=0; i<edit.length; i++){ edit[i].addEventListener('click', function(){ alert(this.getAttribute("id")); }) };	
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

等待DOMContentLoaded事件:

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code here.
});