我有一个javascript ajax函数,它从我的数据库中获取一些信息,并使用此信息中的标题和img源创建新的li元素。每个图像在创建时也会被赋予id。
我的问题是我希望能够点击每个图像来触发一个功能,但是当我尝试通过它的id访问每个图像时,我在控制台中得到一个“无法设置属性'onlick'的null错误
以下是代码:
Ajax功能:
function loadNavbar() {
//Load layer list from WRL.
var navbar_list = new Nfis.Ajax.Wrl('carouselNavBarLocal',
"http://local.ol.nfis.org/wrl/resource", {
'domain' : 'nfis'
});
var length = navbar_list.length;
navbar_list.events.register("onResponse", this, function() {
var wrNavbar_List = navbar_list.getList();
var counter = 1;
//Grab the ul and li elements from the HTML Page
var ul=document.getElementById('ul-navbar');
//For each navbar element in the wrl list, we need to create and
// set the map title and image source.
for ( var i in wrNavbar_List) {
//we also need to grab the associated namespace and map title
// for loading the overlay_map layers and changing the title later.
namespaces.push(wrNavbar_List[i].getUrl2());
map_titles.push(wrNavbar_List[i].getTitle(lang));
//Creation and Setting of title and image source for each li element.
var navbar_h3 = document.createElement('h3');
var navbar_img = document.createElement('img');
navbar_h3.innerHTML = wrNavbar_List[i].getTitle(lang);
navbar_img.src = wrNavbar_List[i].getUrl();
navbar_img.id = "test"+counter;
counter++;
//Creation of each li element
var li = document.createElement('li');
li.appendChild(navbar_h3);
li.appendChild(navbar_img);
ul.appendChild(li);
}
});
//
//navbar_list.fetchList();
}
我的脚本底部是onclick功能:
//Two tests for testing loading in forest cover overlay layers
// and removeMapLayers() function
document.getElementById('test1').onclick = function() {
alert('test');
if (lang === 'fr') {
changeMapTitle('Carte de la couverture forestière');
} else {
changeMapTitle('Canada Forest Cover Map');
}
loadOverlayLayers('forestCoverLayersLocal');
reloadMap();
}
document.getElementById('test3').onclick = function() {
if (lang === 'fr') {
changeMapTitle('Test des couches de base');
} else {
changeMapTitle('Canada Forest Cover Map');
}
removeOverlayLayers(mapLayers);
}
我今天大部分时间都试图解决这个问题无济于事。我已经尝试过window.onload(),callbacks和$(document).ready(function)之类的东西。请帮我!
答案 0 :(得分:-1)
只是因为其他人遇到这个问题我找到了解决办法:
将两次点击测试放在" onresponse" for循环之后的回调我能够在创建所有li元素后强制执行click函数。
这是更新后的代码:
class AppDelegate: NSObject, NSApplicationDelegate{
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSURLProtocol.registerClass(TestURLProtocol)
Alamofire.request(.GET, SomeURL).responseSwiftyJSON({ (request, response, json, error) in })
}
}
class TestURLProtocol: NSURLProtocol {
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
print("request \(request.URL!)") // never called
return false
}
}