javascript 向使用 document.createElement 创建的元素添加事件处理程序(带参数)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3302344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:47:13  来源:igfitidea点击:

Adding event handler (with parameters) to element created using document.createElement

javascript

提问by Fikre

In the function below I'm trying to create a dynamic element (textArea). I'm trying to bind a function (resize)to the text area using textArea.onclick = resize;which works fine.

在下面的函数中,我试图创建一个动态元素(textArea)。我正在尝试使用textArea.onclick = resize;将函数(调整大小)绑定到文本区域这工作正常。

What I'd like to do is pass a parameter to the resize function (either the generated id or, if possible, the textArea itself)

我想要做的是将参数传递给 resize 函数(生成的 id 或者,如果可能的话,textArea 本身)

    function addElement(elm, event) {
        var textArea = document.createElement('textarea');
        var id = Math.random();
        textArea.setAttribute('id', id)
        textArea.setAttribute('cols', 1);
        textArea.setAttribute('rows', 3);
        textArea.onclick = resize;
        elm.appendChild(textArea);
    }

if I say textArea.onclick = resize(id);then that just calls the function.

如果我说textArea.onclick = resize(id); 那么这只是调用该函数。

How can i bind the function, and pass a parameter to it?

如何绑定函数,并向其传递参数?

回答by MooGoo

Use a closure:

使用闭包:

textArea.onclick = function() { resize(id); };

Or use the elements id attribute:

或者使用元素 id 属性:

textArea.onclick = function() { resize(this.id); };

回答by Anurag

You can access the id, and the textarea from the event object itself. In the resize function, access the textarea, and subsequently the id as:

您可以从事件对象本身访问 id 和 textarea。在调整大小函数中,访问 textarea,然后访问 id 为:

function resize(event) {
    var textarea = event.target;
    var id = textarea.id;
}

回答by naikus

You can create a function called resize from another function.

您可以从另一个函数创建一个名为 resize 的函数。

     function addElement(elm, event) {
        var textArea = document.createElement('textarea');
        var id = Math.random();
        textArea.setAttribute('id', id)
        textArea.setAttribute('cols', 1);
        textArea.setAttribute('rows', 3);
        textArea.onclick = createResizeFunction(textArea); // assign resize 
                                                           //function 
        elm.appendChild(textArea);
     }

     function createResizeFunction(textArea)  {
        var resize = function() {
           var id = textArea.id;
           // do something with that id
        };
        return resize;
     }