简体   繁体   中英

Anonymous function error : SyntaxError: Unexpected end of input

I'm dynamically creating DOM elements in my Javascript code, and I am trying to add an anonymous function as an onclick event handler. Here is my code :

var onClickFunction = "(function(){var x = document.getElementById('onPrsClickButton'); x.value = this.id; x.click();})()";

var libelle = '<div onclick=' + onClickFunction + '></div>'

But whenever I click this <div> , the console gives me this error :

SyntaxError: Unexpected end of input

Does anyone know why ? Thanks !

The printed output will be

<div onclick=(function(){var x = document.getElementById('onPrsClickButton'); x.value = this.id; x.click();})()></div>

This is not a valid HTML property value.
To make it valid you must surround the value in quotation marks (") or apostrophes (').
Some browsers can withstand some level of abuse, like not writing proper syntax, but that can't be trusted.

Also, your code have a IIFE (Immediately Invoked Function Expression). This means that the code inside the function will be executed right away, not when you click (although I'm not sure the actual behavior in this particular case).

To make your sample work, you can do something like this:

var onClickFunction = function(){
    // Your event handler
};

var libelle = '<div onclick="javascript:onClickFunction();"></div>'

But the best approach (IMO) to solve your problem is to add a listener to your click, like this:

var libelle = document.getElementById("libelle");
libelle.addEventListener('click', function(){
    // Your event handler
});

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