I want to change a Javascript variable in onClick action.
but my console return this error message: Uncaught SyntaxError: function statement requires a name
I don’t known why js behavior.
My codes below:
const table_body = document.querySelector('.table_body');
let color = 550;
const createTable = function() {
const tableAdd_HTML = '<button class="funcBtn" onclick="javascript:(function() { alert("color changed"); color = 3; })()">Run js function in onClick action</button>';
table_body.innerHTML = tableAdd_HTML;
}
.funcBtn{
width: 160px;
height: 80px;
background-color: red;
color: white;
position:absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<button type="button" onClick="createTable()">Create Table</button>
<div class="table_body"></div>
It is very interesting for me to know why this code behaves like this, Thanks.
>Solution :
The first quote in alert("color changed") is matching the quote in onclick=", so it’s ending the attribute.
Use single quotes in the attribute so they don’t match the attribute delimiter.
Then you need to ensure that this doesn’t conflict with the quotes that delimit the entire HTML string. You could escape the single quotes, but a simple solution is to make the string a template literal.
const table_body = document.querySelector('.table_body');
let color = 550;
const createTable = function() {
const tableAdd_HTML = `<button class="funcBtn" onclick="javascript:(function() { alert('color changed'); color = 3; })()">Run js function in onClick action</button>`;
table_body.innerHTML = tableAdd_HTML;
}
.funcBtn{
width: 160px;
height: 80px;
background-color: red;
color: white;
position:absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<button type="button" onClick="createTable()">Create Table</button>
<div class="table_body"></div>
You can avoid all these quoting problems by using DOM objects instead of HTML strings and inline JavaScript.
const table_body = document.querySelector('.table_body');
let color = 550;
const createTable = function() {
const button = document.createElement("button");
button.classList.add("funcBtn");
button.addEventListener("click", function() {
alert("color changed");
color = 3;
});
button.innerText = "Run js function to change color";
table_body.innerHTML = '';
table_body.appendChild(button);
}
.funcBtn {
width: 160px;
height: 80px;
background-color: red;
color: white;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<button type="button" onClick="createTable()">Create Table</button>
<div class="table_body"></div>