简体   繁体   中英

Wrapped clickable DivElement : event isn't listened

Please, consider the little following code :

function Movable(x, y, width, height, background_color) {
    this.html_element = document.createElement("div");

    this.html_element.onclick = this.move;
    this.move = function() {
        alert("Clicked !");
    };

    this.display = function() {
        document.body.innerHTML += this.html_element.outerHTML;
    };
}

I'm trying to add the HTML attribute "onclick" with "move();" as value. This move value is actually a function that alerts "Clicked !" when the final-user clicks on this HTML element.

But it doesn't work. When I inspect the source, it seems that the property onclick isn't added to this HTML element.

Do you know why and how I could solve this problem ?

document.body.innerHTML += this.html_element.outerHTML; is the problem. That's just about the worst way to go about adding an element to a page.

Your handler has nothing to do with HTML, so it is being lost when you serialize the element to HTML with the outerHTML call. Not to mention that you're serializing and destroying all the nodes under the document.body , and then turning them back into new nodes, which will make them lose handlers and other data too.

Instead just do use .appendChild() to add the Element node:

document.body.appendChild(this.html_element)

Also, you're assigning this.move as the handler before you create it, which will just assign undefined unless there's a Movable.prototype.move with a handler.

function Movable(x, y, width, height, background_color) {
    this.html_element = document.createElement("div");

    this.move = function() {
        alert("Clicked !");
    };

    this.html_element.onclick = this.move;

    this.display = function() {
        document.body.appendChild(this.html_element);
    };
}

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