Javascript onclick parameter

前端 未结 2 1608
[愿得一人]
[愿得一人] 2021-01-28 15:07

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


相关标签:
2条回答
  • 2021-01-28 15:38

    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.

    0 讨论(0)
  • 2021-01-28 15:47

    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);
    
    0 讨论(0)
提交回复
热议问题