开发者

Creating paragraphs based on user input

I'm having trouble, grabbing the user input, and having the onclick operator create additional paragraphs with each click.

Here is my HTML code.

    <!DOCTYPE html>

    <html lang='en'>
    <head>
    <title>Add Paragraph </title>
    <meta charset='utf-8' >
    <script src="../js/addPara.js" type="text/javascript"></script>
    </head>  
    <body>
    <div>
    <input type='text' id='userParagraph' size='20'>
    </div>

    <div id="par">

    <button id='heading'> Add your paragraph</button> 
    </div>
    </body>
    </html>

Here is Javascript code: 

window.onload = function() {
  document.getElementById("addheading").onclick开发者_StackOverflow社区 = pCreate;
};

    function pCreate() {
      var userPar= document.createElement("p");
      var parNew = document.getElementById('userParagraph').value;
      userPar.innerHTML = par;
      var area = document.getElementById("par");
      area.appendChild(userPar);
}


userPar.innerHTML = par;

should be

userPar.innerHTML = parNew;


In your code:

> window.onload = function() {  
>   document.getElementById("addheading").onclick = pCreate;
> };

Where it is possible (perhaps likely) that an element doesn't exist, best to check before calling methods:

    var addButton = document.getElementById("addheading");

    if (addButton) {
      addButton.onclick = pCreate;
    }

Also, there is no element with id "addheading", there is a button with id "heading" though.

> function pCreate() {
>   var userPar= document.createElement("p"); 
>   var parNew = document.getElementById('userParagraph').value;  
>   userPar.innerHTML = par;

I think you mean:

    userPar.innerHTML = parNew;

if you don't want users inserting random HTML into your page (perhaps you do), you can treat the input as text:

    userPar.appendChild(document.createTextNode(parNew));

.

>   var area = document.getElementById("par"); 
>   area.appendChild(userPar);
> }

Your variable names and element ids don't make a lot of sense, you might wish to name them after the data or function they represent.


I did it and it worked.


   <html lang='en'>
   <head>
   <title>Add Paragraph </title>
   <meta charset='utf-8' >
   <script>
    window.onload = function() {
  document.getElementById("heading").onclick = pCreate;
}

    function pCreate() {
      var userPar= document.createElement("p");
      var parNew = document.getElementById('userParagraph').value;
      userPar.innerHTML = parNew;
      var area = document.getElementById("par");
      area.appendChild(userPar);
}
   </script>
   </head>
   <body>
   <div>
   <input type='text' id='userParagraph' size='20'>
   </div>

   <div id="par">

   <button id='heading'> Add your paragraph</button>
   </div>
   </body>
   </html>```
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜