Created
March 16, 2023 19:10
-
-
Save bellrd/74e2bb29318a3a602122aa32a2e5ab1d to your computer and use it in GitHub Desktop.
Setting attribute 'onclick' on html element using javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
</head> | |
<body> | |
<!-- <button onclick="del('7');"> click to delete</button> --> | |
<div id="content"></div> | |
<script> | |
let state = ["cat", "dog", "elephant","ant"]; | |
function echo(name) { | |
console.log(name + 7); | |
} | |
state.forEach((v, index)=> { | |
let b = document.createElement("button"); | |
b.innerText = v.toUpperCase(); | |
// b.setAttribute("onclick", `echo(${index})`); | |
b.onclick = function() { | |
echo(index); | |
} ; | |
document.getElementById("content").appendChild(b); | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment