2017-06-17 47 views
0

我使用xmlhttprequest获取'cars'数组并为数组中的每个值动态创建锚定标记。访问动态创建的锚定标记

现在我无法访问新创建的锚标签的innerhtml。

//script for getting array and creating anchor tags dynamically 

var xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange = function() { 
if (this.readyState == 4 && this.status == 200) {  
var cars = JSON.parse(xmlhttp.responseText); 
for (i = 0; i < cars.length; i++) 
{ 
var mydiv = document.getElementById("myDiv"); 
var aTag = document.createElement('a'); 
aTag.setAttribute('href','#'); 
aTag.setAttribute('class','cl'); 
aTag.innerHTML = cars[i] + "<br>"; 
mydiv.appendChild(aTag); 
} 

} 
}; 

xmlhttp.open("POST", "http://localhost:3000/welcomepage", true); 
xmlhttp.setRequestHeader("Content-type", "application/json"); 
xmlhttp.send(); 


//script for accessing innerhtml of the above created anchor tags. 

$('.cl').click(function(e) { 
e.preventDefault(); 
var t = $(this).text(); 
alert(t); 
} 

回答

0
  1. 使用.post的$替代的XMLHTTP
  2. 使用代表团In jQuery, how to attach events to dynamic html elements?
  3. 注意到我如何使用$。每个
//script for getting array and creating anchor tags dynamically 
// not tested but should be ok depending on return values 

$.post("http://localhost:3000/welcomepage", function(cars) { 

    var $mydiv = $("#myDiv"), 
    carHTML = []; 
    $.each(cars, function(car) { // or function(_,car) - not clear from question 
    carHTML.push($('<a/>', { 
     'href': '#', 
     'class': 'cl' 
    }).html(car)); 
    }); 
    $mydiv.append(carHTML.join('<br/>')); 
}); 

//script for accessing innerText of the above created anchor tags. 

$("#myDiv").on("click", ".cl", function(e) { 
    e.preventDefault(); 
    var t = $(this).text(); 
    alert(t); 
}); 
+1

我必须包括$(“# myDiv“)。也使用xmlhttp ..非常感谢你... –