javascript基礎-《web前端最佳實務》

來源:互聯網
上載者:User

標籤:text   百度   rem   元素   html5   web前端   顯示   載入   name   

先貼代碼

 1     <form action=""> 2         <p> 3             <label for="x">Number:</label> 4             <input id="x" name="x" type="number" /> 5         </p> 6         <input id="submit" type="submit" value="Calculat Square" /> 7         <script> 8         var x = document.getElementById(‘x‘); 9         var output = document.createElement(‘p‘);10         output.textContent = ‘Type a number; it will be squared right then!‘;11 12         x.form.appendChild(output);13         x.form.onsubmit = function(){return false;};14         x.oninput = function(){15             var v = x.valueAsNumber;16             output.textContent = v + ‘ squared is ‘ + v*v;17         };18 19         var submit = document.getElementById(‘submit‘);20         submit.parentNode.removeChild(submit);21         </script>22     </form>

這段代碼是求平方,javascript起作用時通過JS計算直接顯示在頁面,頁面禁止載入JS時通過submit提交(參考noscript)。這裡只記錄基礎JS。

 

第9行,createElement()方法會建立一個元素節點,通常添加文本,故後面緊接著賦值output.textContent = ‘‘;然後插入顯示x.form.appendChild(output);百度的時候看到另一種用法一起貼過來

1 var btn=document.createElement("BUTTON");    //建立元素節點2 var t=document.createTextNode("CLICK ME");    //建立文本節點3 btn.appendChild(t);    //將文本節點添加到元素中

第15行,valueAsNumber是HTML5新增,可以讀取元素內數值,但是要配合<input type="number" />使用,否則會報NAN錯誤。

 

javascript基礎-《web前端最佳實務》

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.