简体   繁体   中英

Creating Html Element with onclick() event in javascript

I've been working at this for the last hour, but I am still unable to get the expected output... All I want is to create an HTML element using the onclick event. I was able to create the element on load, but find myself unable to with the event. Please lead me in the right direction. Here's my HTML page:

<html>
<body>

    <div id="d1">
        <p id="p1">Paragraph.</p>

    </div>
    <div id="d2">
        <label onclick="open()">Inbox</label>
    </div>

    <script>
        function open(){
            alert("Start");
            var para=document.createElement("p");
            var node=document.createTextNode("Text");
            para.appendChild(node);
            para.style.color="red";
            var element=document.getElementById("d2");
            element.appendChild(para);
                       }
    </script>

    </body>
</html>

open() seems to be a reserved functions. Tried with open1() , it works.

您可能正在与浏览器中内置的window.open函数发生冲突,重命名您的函数。

Try this code

<label onclick="create_elem();">Inbox</label>
<script language="javascript">
function create_elem(){
    alert("Start");
    var para=document.createElement("p");
    var node=document.createTextNode("Text");
    para.appendChild(node);
    para.style.color="red";
    var element=document.getElementById("d2");
    element.appendChild(para);
}
</script>

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