简体   繁体   中英

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

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.

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

    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.

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

Use a closure:

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

Or use the elements id attribute:

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

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:

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

You can create a function called resize from another function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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