简体   繁体   English

我如何使用JavaScript在html中隐藏div来简化代码?

[英]How do i simplify my code, hiding div's in html using javascript?

I am very new to JavaScript and i'm struggling to find a solution to simplify my JavaScript code. 我对JavaScript还是很陌生,我一直在努力寻找一种简化我的JavaScript代码的解决方案。 I have working code, but it's very bulky and i feel like it can be made smaller or easier. 我有有效的代码,但是它非常庞大,我觉得可以将它做得更小或更容易。 Do you guys think it's possible? 你们认为有可能吗?

I have went online and tried to see if i can implement what people have done, but most of the stuff either don't work or works but is not what i'm looking for. 我上网了,试图看看我是否可以执行人们所做的事情,但是大多数东西要么不起作用,要么就不起作用,但这不是我想要的。

<html>
    <script>
        window.onload = function () {

    document.getElementById("Yes1").onclick = function () {
    document.getElementById("Question1").style.display = 'None';
    document.getElementById("Question2").style.display = 'inline';
    }
    document.getElementById("No1").onclick = function () {

    document.getElementById("Question1").style.display = 'None';
    document.getElementById("Question3").style.display = 'inline';
    }      
    document.getElementById("Yes2").onclick = function () {

    document.getElementById("Question2").style.display = 'None';
    document.getElementById("Question4").style.display = 'inline';
    }

    document.getElementById("No2").onclick = function () {

    document.getElementById("Question2").style.display = 'None';
    document.getElementById("Question5").style.display = 'inline';
    }

    document.getElementById("Yes3").onclick = function () {

    document.getElementById("Question3").style.display = 'None';
    document.getElementById("Question6").style.display = 'inline';
    }

    document.getElementById("No3").onclick = function () {

    document.getElementById("Question3").style.display = 'None';
    document.getElementById("Question6").style.display = 'inline';
    }

    document.getElementById("Yes4").onclick = function () {

    document.getElementById("Question4").style.display = 'None';
    document.getElementById("Question10").style.display = 'inline';
    }
    document.getElementById("No4").onclick = function () {

    document.getElementById("Question4").style.display = 'None';
    document.getElementById("Question10").style.display = 'inline';
    }
    document.getElementById("Yes5").onclick = function () {

    document.getElementById("Question5").style.display = 'None';
    document.getElementById("Question10").style.display = 'inline';
    }
    document.getElementById("No5").onclick = function () {

    document.getElementById("Question5").style.display = 'None';
    document.getElementById("Question10").style.display = 'inline';
    }
    document.getElementById("Yes6").onclick = function () {

    document.getElementById("Question6").style.display = 'None';
    document.getElementById("Question7").style.display = 'inline';
    }
    document.getElementById("No6").onclick = function () {

    document.getElementById("Question6").style.display = 'None';
    document.getElementById("Question8").style.display = 'inline';
    }
    document.getElementById("Yes7").onclick = function () {

    document.getElementById("Question7").style.display = 'None';
    document.getElementById("Question9").style.display = 'inline';
    }
    document.getElementById("No7").onclick = function () {

    document.getElementById("Question7").style.display = 'None';
    document.getElementById("Question9").style.display = 'inline';
    }
    document.getElementById("Yes8").onclick = function () {

    document.getElementById("Question8").style.display = 'None';
    document.getElementById("Question9").style.display = 'inline';
    }
    document.getElementById("No8").onclick = function () {

    document.getElementById("Question8").style.display = 'None';
    document.getElementById("Question9").style.display = 'inline';
    }
    document.getElementById("No9").onclick = function () {

    document.getElementById("Question9").style.display = 'None';
    document.getElementById("Question10").style.display = 'inline';
    }
    document.getElementById("No9").onclick = function () {

    document.getElementById("Question9").style.display = 'None';
    document.getElementById("Question10").style.display = 'inline';
    }

           }
    </script>
    <body>
        <section>
            <article>
                <hgroup>
                   <h1>Dynamic Questionnaire</h1>
                    <h2>Question disappear after clicked</h2>
                </hgroup>
              <div id="Test1" >
                1.1. ...
                    <input type='radio' id='Yes1' name='answer1'> Yes
                    <input type='radio' id='No1' name='answer1'> No
              </div>
              <div id="Test2" >
                1.2. ...
                    <input type='radio' id='Yes1' name='answer1'> Yes
                    <input type='radio' id='No1' name='answer1'> No
              </div>
                <div id="Question1">
                    1. ....
                    <input type='radio' id='Yes1' name='answer1'> Yes
                    <input type='radio' id='No1' name='answer1'> No
                </div>
                <div id="Question2" style='display:none' >
                    2. ....
                    <input type='radio' id='Yes2' name='answer1'> Yes
                    <input type='radio' id='No2' name='answer1'> No
                </div>
                <div id="Question3" style='display: none'>
                    3. ....
                    <input type='radio' id='Yes3' name='answer1'> Yes
                    <input type='radio' id='No3' name='answer1'> No
                </div>
                <div id="Question4" style='display: none'>
                    4. ....
                    <input type='radio' id='Yes4' name='answer1'> Yes
                    <input type='radio' id='No4' name='answer1'> No
                </div>
                <div id="Question5" style='display: none'>
                    5. ....
                    <input type='radio' id='Yes5' name='answer1'> Yes
                    <input type='radio' id='No5' name='answer1'> No
                </div>
                <div id="Question6" style='display: none'>
                    6. ....
                    <input type='radio' id='Yes6' name='answer1'> Yes
                    <input type='radio' id='No6' name='answer1'> No
                </div>
                <div id="Question7" style='display: none'>
                    7. ....
                    <input type='radio' id='Yes7' name='answer1'> Yes
                    <input type='radio' id='No7' name='answer1'> No
                </div>
                <div id="Question8" style='display: none'>
                    8. ....
                    <input type='radio' id='Yes8' name='answer1'> Yes
                    <input type='radio' id='No8' name='answer1'> No
                </div>
                <div id="Question9" style='display: none'>
                    9. ....
                    <input type='radio' id='Yes9' name='answer1'> Yes
                    <input type='radio' id='No9' name='answer1'> No
                </div>
                <div id="Question10" style='display: none'>
                    10. ....
                    <input type='radio' id='Yes10' name='answer1'> Yes
                    <input type='radio' id='No10' name='answer1'> No
                </div>
            </article>
        </section>
    </body>
</html>

[Sorry if i pasted too much code, can still barely use StackOverflow] So, when i run my html file, when the first Question appears, it has 'yes' and 'no' radio buttons.And when i click yes it should go to question 2 but hide question 1. And if i click no, it should hide question 1 as well but go to question 3. PS: I removed some html tags [很抱歉,如果我粘贴了太多代码,仍然几乎不能使用StackOverflow]因此,当我运行html文件时,当第一个问题出现时,它具有“是”和“否”单选按钮。当我单击“是”时,它应该转到问题2,但隐藏问题1。如果我单击否,它也应隐藏问题1,但转到问题3。PS:我删除了一些html标签

Welcome to Javascript! 欢迎使用Javascript! Don't worry about being new, everyone was new once :) 不用担心成为新人,每个人都曾经是新人:)

A few pointers that should help learn too 一些也应该帮助学习的指针

You can only have 1 element with a paricular id, so 您只能有1个具有特殊ID的元素,因此

<input type='radio' id='Yes1' name='answer1'> Yes
<input type='radio' id='No1' name='answer1'> No

is fine but 很好,但是

 <input type='radio' id='Yes1' name='answer1'> Yes
 <input type='radio' id='No1' name='answer1'> No
</div>
<div id="Test2" >
 1.2. ...
  <input type='radio' id='Yes1' name='answer1'> Yes
  <input type='radio' id='No1' name='answer1'> No

would need to be changed to (difference in the id fields) 将需要更改为( id字段中的差异)

 <input type='radio' id='Yes11' name='answer1'> Yes
 <input type='radio' id='No11' name='answer1'> No
</div>
<div id="Test2" >
 1.2. ...
  <input type='radio' id='Yes12' name='answer1'> Yes
  <input type='radio' id='No12' name='answer1'> No

Now this makes things more complex! 现在,这使事情变得更加复杂! We have to address each individually in the code...far from helpful...enter class es. 我们必须在代码中单独解决每个问题……远没有帮助……输入class es。

Assign each 'set' of answers (or block) a class to help differentiate the semantics of each set. 为答案(或答案)的每个“集合”分配一个类,以帮助区分每个集合的语义。

          <div id="Test1" >
            1.1. ...
                <input type='radio' class='test1 answer-yes' name='answer1'> Yes
                <input type='radio' class='test1 answer-no' name='answer1'> No
          </div>
          <div id="Test2" >
            1.2. ...
                <input type='radio'  class='test2 answer-yes' name='answer1'> Yes
                <input type='radio' class='test2 answer-no' name='answer1'> No
          </div>

In this case, without using libraries, it's probably useful to store the required "action" on the "event input". 在这种情况下,不使用库,将所需的“操作”存储在“事件输入”上可能很有用。 For this we can use the data- attribute on an HTML element, and access it from the Javascript (we can also use something semantic, like the name ): 为此,我们可以在HTML元素上使用data-属性,并从Javascript访问它(我们也可以使用一些语义,例如name ):

          <div id="Test1" >
            1.1. ...
                <input type='radio' data-action="1"  class='test1 answer-action answer-yes' name='answer1' data> Yes
                <input type='radio' data-action="1"  class='test1 answer-action answer answer-no' name='answer1'> No
          </div>

Also the answer class name has been added to suggest that this answer provides some action. 此外,还添加了answer类别名称,以表明该答案提供了一些措施。 To find all our answers with actions, in your javascript you can generically address all of the elements (pulled from question https://stackoverflow.com/a/40956816/5746996 : 要找到我们所有具有行动的答案,可以在您的JavaScript中通用地解决所有元素(从问题https://stackoverflow.com/a/40956816/5746996中拉出:

var elementsArray = document.querySelectorAll('answer-action');

elementsArray.forEach(function(elem) {
    elem.addEventListener("click", function() {
        //do something 
        elem.dataset.action // gives you the relevant action
    });
});

First, id values must be unique within a document and you are reusing the same ones for each set of radio buttons, so you'll need to correct that. 首先, id值在文档中必须是唯一的,并且您要为每组单选按钮重复使用相同的值,因此您需要进行更正。 Now, the name attribute on each of the radio buttons within a set should be the same, but the next set need a different name so that the answer from one question doesn't get overridden by the answer to the next. 现在,一组中每个单选按钮的name属性应该相同,但是下一组需要一个不同的名称,这样一个问题的答案就不会被下一个问题的答案所取代。 You also need to give each radio button a value so that if it is selected, that selection will have meaning. 您还需要为每个单选按钮赋予一个value以便如果选择它,那么该选择将具有含义。 (I've used "Yes" and "No" below, but more specific values that relate to the question should be used when appropriate.). (我在下面使用了“是”和“否”,但是在适当的时候应该使用与该问题相关的更具体的值。)

But, frankly, the best way to create better code here is to not rely in inline styles and id s in the first place. 但是,坦率地说,在此处创建更好的代码的最佳方法是首先不要依赖于内联样式和id It bulks up the HTML and forces you to deal with each id separately. 它会放大HTML,并迫使您分别处理每个id

Instead, just assign CSS classes to each question element and style the elements dynamically with that class. 相反,只需将CSS类分配给每个问题元素,然后使用该类动态设置元素的样式。 See the comments inline below and note how much simpler the code is. 请参阅下面的内联注释,并注意代码更简单。

I've wrapped the actual text of each question in a span element to make it easy to gain access to the question text later if desired. 我将每个问题的实际文本包装在span元素中,以便以后在需要时可以轻松访问问题文本。

Also, instead of setting up a window.onload event handler, just move your script to the bottom of the HTML, just prior to the closing body tag ( </body> ). 另外,除了设置window.onload事件处理程序外,只需将script移动到HTML的底部,紧接在结束body标签( </body> )之前即可。 That way, by the time the HTML parser encounters your script, all of the HTML will have been loaded. 这样,当HTML解析器遇到您的脚本时,所有HTML都将被加载。

Lastly, the hgroup element is part of the WHAT WG HTML5 standard, but it is not part of the W3C HTML5 standard and as such, you should probably avoid using it. 最后, hgroup元素是WHAT WG HTML5标准的一部分,但不是W3C HTML5标准的一部分,因此,您应该避免使用它。

 .hidden { display:none; } .question { border:1px dashed #e0e0e0; } .results { border:1px solid #909090; background-color:rgba(0,0,0,.25);} 
 <html> <body> <section> <article> <h1>Dynamic Questionnaire</h1> <h2>Question disappear after clicked</h2> <div class="question"> <span class="questionText">1. ....</span> <input type='radio' name='answer1' value="Yes"> Yes <input type='radio' name='answer1' value="No"> No </div> <div class="question hidden"> <span class="questionText">2. ....</span> <input type='radio' name='answer2' value="Yes"> Yes <input type='radio' name='answer2' value="No"> No </div> <div class="question hidden"> <span class="questionText">3. ....</span> <input type='radio' name='answer3' value="Yes"> Yes <input type='radio' name='answer3' value="No"> No </div> <div class="question hidden"> <span class="questionText">4. ....</span> <input type='radio' name='answer4' value="Yes"> Yes <input type='radio' name='answer4' value="No"> No </div> <div class="question hidden"> <span class="questionText">5. ....</span> <input type='radio' name='answer5' value="Yes"> Yes <input type='radio' name='answer5' value="No"> No </div> <div class="question hidden"> <span class="questionText">6. ....</span> <input type='radio' name='answer6' value="Yes"> Yes <input type='radio' name='answer6' value="No"> No </div> <div class="question hidden"> <span class="questionText">7. ....</span> <input type='radio' name='answer7' value="Yes"> Yes <input type='radio' name='answer7' value="No"> No </div> <div class="question hidden"> <span class="questionText">8. ....</span> <input type='radio' name='answer8' value="Yes"> Yes <input type='radio' name='answer8' value="No"> No </div> <div class="question hidden"> <span class="questionText">9. ....</span> <input type='radio' name='answer9' value="Yes"> Yes <input type='radio' name='answer9' value="No"> No </div> <div class="question hidden"> <span class="questionText">10. ....</span> <input type='radio' name='answer10' value="Yes"> Yes <input type='radio' name='answer10' value="No"> No </div> </article> </section> <section class="results hidden"><div>Summary of Answers:</div></section> <script> // Get all the question elements into an array let questions = Array.prototype.slice.call(document.querySelectorAll(".question")); // Loop through the questions questions.forEach(function(question){ // Set up a click event handler for the question question.addEventListener("click", function(){ this.classList.add("hidden"); // Hide the current question // Show the next question (if there is one) if(this.nextElementSibling){ this.nextElementSibling.classList.remove("hidden"); } else { // All questions have been answered at this point. // Proceed as you see fit. Here, I'm just displaying // a summary of each question with the supplied answer // for demonstration: let output = document.querySelector(".results"); // Get reference to the results area let outputString = ""; // <-- Will hold output to be written to results area // Loop through the questions questions.forEach(function(quest){ // Build up a string consisting of the question itself a colon, the value // of the selected radio button for that question and an HTML break tag outputString += quest.firstElementChild.textContent + " : " + quest.querySelector("input[type='radio']:checked").value + "<br>"; }); output.innerHTML += outputString; // Inject the output string into the resluts area output.classList.remove("hidden"); // Show the results area } }); }); </script> </body> </html> 

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

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