Javascript onclick parameter

人盡茶涼 提交于 2021-02-05 11:09:55

问题


I have a question about "onclick" function in JavaScript. Here I have a div "InfoBar"

<div id="InfoBar"><br>

and two for loop

 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]);
 }

and a doesFileExist() and klick function

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>';
}

now I've added a "onclick" function in "a href".

if I click on "link1:el1", I want to display as alert "urlToFile" string. But I doesn't work.

In "a href" title="'+urlToFile+'" it works perfect, but in "onclick" doesn't work.

Can anyone help me? Thanks in advance.


回答1:


You are generating an attribute. That gets converted back into a function but the scope is broken.

  • Don't use intrinsic event attributes.
  • Minimise use of globals
  • Avoid generating HTML by mashing strings together (at best it is hard to read, at worst you get this sort of issue)

Use standard 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);



回答2:


Event handles assigned this way won't work. You have to use JavaScript event handles. Means, you must create a new 'a' element, then bind a click event to it, and then append it as a child to the parent node. All this stuff is very good described on the web out there.



来源:https://stackoverflow.com/questions/26777077/javascript-onclick-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!