简体   繁体   English

如何通过javascript中创建的链接运行函数

[英]How to run a function from a link created in javascript

I have a function in a javascript file that adds a link to a paragraph that I created in the HTML file. 我在javascript文件中有一个函数,该函数向我在HTML文件中创建的段落添加了链接。 I want to call a function that is defined in the javascript file when the user clicks the link. 当用户单击链接时,我想调用javascript文件中定义的函数。

My HTML: 我的HTML:

<p id="para"></p>

My JavaScript: 我的JavaScript:

var paraHTML = document.getElementById("para");

function addLink(id) {
    paraHTML.innerHTML += '<a id="' + id + '" onclick="clickedTest(); return false;">Click me!</a>'
}

function clickedTest() {
    console.log('here');
}

I have also tried using href eg 我也尝试过使用href例如

paraHTML.innerHTML += '<a id="' + id + '" href="javascricpt:clickedTest();">Click me!</a>'

But both ways give me an error saying: ReferenceError: clickedTest is not defined 但是两种方式都给我一个错误,说: ReferenceError: clickedTest is not defined

I have tried using the following code from this question but the number of links is constantly changing whilst my code is running which makes it difficult to use: 我已经使用从下面的代码试过这个问题,但链接的数量是不断变化的,而我的代码运行,这使得它很难使用:

var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
    elements[i].onclick = function () {
        console.log('here')
    }
}

The addLink() function is called elsewhere in my javascript program several times 在我的javascript程序中的其他位置多次调用addLink()函数

Using innerHTML to create content is usually slow and is usually discouraged, a more organic approach will be to create the element pragmatically and then adding event listener to that element. 使用innerHTML创建内容通常很慢,并且通常不鼓励使用,更有机的方法是实用地创建元素,然后向该元素添加事件侦听器。 For example, 例如,

var elem = document.createElement('a');
elem.addEventListener('click', myClickHandler);
elem.innerText = 'My Tag';
paraHTML.appendChild(elem)

function myClickHandler(e) {
  console.log('a is clicked')
}

This will not only fix your problem but will make your code more manageable 这不仅会解决您的问题,还将使您的代码更易于管理

You can do something like this: 您可以执行以下操作:

 function callMe(){ } var newLink = document.createElement('a'); newLink.href="javascript:callMe();"; newLink.innerHTML="this is a link"; paraHTML.appendChild(newLink); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM