我对JavaScript中的"onclick"
函数有疑问。我有一个div "InfoBar"
<div id="InfoBar"><br>
和两个for循环
var src = new Array();
for(var i = 0; i < 2; i++){
src.push("el1","el2");
}
for(var j = 0; j < 2; j++){
doesFileExist(src[j]);
}
和一个doFileExist()和klick函数
function klick(el){
alert(el)
}
function doesFileExist(urlToFile){
document.getElementById('InfoBar').innerHTML += '<br>' + '<a id="css" onclick="klick(urlToFile)" href="#" title="'+urlToFile+'">' + "link1 : " + urlToFile + '</a>';
}
现在我在"onclick"
中添加了"a href"
个功能。
如果我点击“link1:el1”,我想显示为alert "urlToFile"
字符串。
但我不行。
在"a href"
title="'+urlToFile+'"
中,它工作得很完美,但"onclick"
无效。
任何人都可以帮助我吗? 提前谢谢。
答案 0 :(得分:1)
您正在生成一个属性。它被转换回函数但范围被打破。
使用标准DOM:
var container = document.getElementById('InfoBar');
container.innerHTML = ""; // Delete any existing content
container.appendChild(document.createElement('br'));
var anchor = document.createElement('a');
anchor.setAttribute('id', 'css'); // You are running this function is a loop and creating duplicate ids. Use a class instead.
anchor.addEventListener('click', function (event) {
klick(urlToFile); // the local variable urlToFile is still in scope
});
anchor.setAttribute('href', '#'); // Why are you linking to the top of the page? Use a <button>
anchor.setAttribute('title', urlToFile);
anchor.appendChild(document.createTextNode("link1 : " + urToFile));
container.appendChild(anchor);
答案 1 :(得分:0)
以这种方式分配的事件句柄不起作用。您必须使用JavaScript事件句柄。意思是,你必须创造一个新的&#39; a&#39; element,然后将click事件绑定到它,然后将其作为子节点附加到父节点。所有这些东西在网上都有很好的描述。