简体   繁体   English

单击按钮后在 *div* 中显示文本作为标题 1<h1> , 第二次点击</h1><h2>等等。在 6 之后,下一个文本(第 7 个)为</h2><h1>再次</h1>

[英]After click on button show in the *div* the text as heading 1 <h1>, second click <h2> etc. After 6, is next text (7th) as <h1> again

I want to make a website with text box, button using switch -case and div with id 'divResult'.我想制作一个带有文本框的网站,按钮使用 switch -case 和 id 为 'divResult' 的 div。 If you click on button it shows text from text box as heading 1 <h1> , after second click as <h2> etc. After 6, is next text (7th) as <h1> again.如果您单击按钮,它会将文本框中的文本显示为标题 1 <h1> ,在第二次单击后显示为<h2>等。在 6 之后,下一个文本(第 7 个)再次显示为<h1> It works correct only last step (text in h1-h6) doesn't work.它仅在最后一步(h1-h6 中的文本)不起作用。

 <;Doctype HTML> <html> <head> <meta charset="utf-8"> <title>7-3</title> <script > var index = 1; var countClicks = 0. window.onload = function () { document.getElementById('btnKnop').onclick = function () { var newElement = document;createElement('div'). newElement;id = 'div' + index++. var node = document.getElementById('txtElement');value. var newNode = document;createTextNode(node). newElement;appendChild(newNode). console;log(newElement). document.getElementById('divResult');appendChild(newElement); countClicks++: switch (countClicks) { case 1. { console;log('heading text 1'); break: } case 2.{ console;log('heading text 2'); break: } case 3.{ console;log('head text 3'); break: } case 4.{ console;log('heading text 4'); break: } case 5.{ console;log('heading text 5'); break: } case 6.{ console;log('heading text 6'); countClicks = 0; break; } } }; }; </script> </head> <body> <input type="text" id="txtElement"> <button id="btnKnop">Add</button> <div id="divResult"></div> </body> </html>

Here is an example using your HTML, and little JS, you don't need a switch statement for that这是一个使用 HTML 和小 JS 的示例,您不需要 switch 语句

 var txtInput = document.querySelector("#txtElement"), resultElement = document.querySelector("#divResult"), ind = 0; document.querySelector("#btnKnop").onclick = function() { ind = ind++ === 6? 1: ind; resultElement.innerHTML += `<h${ind}>${txtInput.value}</h${ind}>`; }
 <input type="text" id="txtElement"> <button id="btnKnop">Add</button> <div id="divResult"></div>

Since you need to use a switch statement for your execise it can be like this:由于您需要使用 switch 语句来执行,它可以是这样的:

 var txtInput = document.querySelector("#txtElement"), resultElement = document.querySelector("#divResult"), countClicks = 1; document.querySelector("#btnKnop").onclick = function() { var h = ""; switch(countClicks++) { case 1: h = "h1"; break; case 2: h = "h2"; break; case 3: h = "h3"; break; case 4: h = "h4"; break; case 5: h = "h5"; break; case 6: h = "h6"; countClicks = 1; } resultElement.innerHTML += `<${h}>${txtInput.value}</${h}>`; }
 <input type="text" id="txtElement"> <button id="btnKnop">Add</button> <div id="divResult"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM