【问题标题】:How does one select the first element of a given class using jquery?如何使用 jquery 选择给定类的第一个元素?
【发布时间】:2014-10-20 23:24:26
【问题描述】:

这是一个调试问题。我已经用谷歌搜索了这个地狱,查看了关于 first() 选择器的 jQuery 文档,并阅读了大量堆栈溢出帖子,但我根据该研究所做的调整都没有奏效。

目标: 在下面的 sn-p 中,我试图从使用 jquery 在 document.ready() 事件顶部添加到 dom 的一系列 div 中的第一个中删除“隐藏”类。

    $(document).on('click','#begin',function(){
        $('#intro').addClass('hidden');
        $('#form').removeClass('hidden');
        $('.question').first().css({'visibility':'hidden'});
    });

问题: 出于某种原因,当我使用 first() 选择器时,所有问题都保持隐藏状态。当我不使用它时,正如预期的那样,所有的问题都会暴露出来。这些 div 是使用带有“问题”和“隐藏”类的 jQuery 动态添加的。

上面的 sn-p 出现在我附加的示例代码的第 50 行。这些类的声明出现在第 30 行。

/**
 * Created by davidgoldberg on 10/16/14.
 */

function Question(topic,question,choices,correctAnswer){
    this.topic = topic;
    this.question = question;
    this.choices = choices;
    this.correctAnswer = correctAnswer;
    this.userAnswer = null;
}

var allQuestions;
allQuestions = [
    new Question("Addition", "What is 8 + 8?", [16, 18, 64, 28], 16),
    new Question("Subtraction", "What is 23-8?", [16, 15, 14, 17], 15),
    new Question("Multiplication", "What is 8 * 8?", [16, 18, 64, 36], 64),
    new Question("Division", "What is 48/16", [3, "3/2", 4, "8/3"], 3),
    new Question("Imaginary Numbers", "What is \u221A(-1)^8?", ["i", "-i", 1, -1], 1)
];


function qToHTML(question) {
    var header = "<h2>" + question.topic + "</h2>";
    var qText = "<p>" + question.question + "</p>";
    var options = "";
    for (var i = 0; i < question.choices.length; i++) {
        options += "<input type='radio' name='" + question.topic + "' value ='" + question.choices[i] + "'>" + question.choices[i] + "<br>";
    }
    var wrapper = "<div class='question'></div>";

    var HTMLstring;
    HTMLstring = header + qText + options;
    $("form").append(HTMLstring).wrap(wrapper);
}



$(document).ready(function(){

    //set up page
    for(var i = 0; i < allQuestions.length; i++){
        qToHTML(allQuestions[i]);
    }
    $('form').append('<input type="submit" value="submit">');
    
    // setup intro
    $(document).on('click','#begin',function(){
        $('#intro').addClass('hidden');
        $('#form').removeClass('hidden');
        $('.question').first().css({'visibility':'hidden'});
    });
    
    // in-form navigation
    $('#next').on('click',function(){

    });

    //collect and check user answers
    $('form').on('submit', function(event) {

        var numCorrect = 0;

        event.preventDefault();

        for(var i = 0; i < allQuestions.length; i++) {

            // collect answers
            var currentQ = allQuestions[i];
            currentQ.userAnswer = $("input[name='" + currentQ.topic + "']:checked").val();

            // check answers
            if (currentQ.correctAnswer == currentQ.userAnswer) {
                numCorrect++;
            }
        }

        // show score
        var score = numCorrect + "/" + allQuestions.length;
        $('#results').find('p').text("You got " + score + " of the questions right");
        $('#results').removeClass('hidden');

        // resets buttons    
        $('input[type="radio"]').each(function(){
            $(this).prop('checked', false);
        });
    });
});
.hidden {
    display: none;
}
<!DOCTYPE html>
<html>
    <head>
        <title>Dynamic Quiz</title>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <h1>Dynamic Quiz</h1>
        
        <div id='intro'>
            <h3>Get ready for the dynamic quiz</h3>
            <p>You will be asked a questions from a range of different math subjects.  Selecting an answer will bring you to the next page.  The 'next' and 'back' buttons do just what you expect.  When you are finished, click the 'submit' button at the bottom of the page, and you will be directed to your score.  When you are ready, click the 'begin' button below.</p>
            <input type="button" id="begin" value="begin">
        </div>

        <div id='form' class='hidden'>
            <form>
                    
                  <!-- <div class="question hidden">
                        <h2></h2>
                        <p></p>
                        <input type="radio" name="" value="">
                        <input type="radio" name="" value="">
                        <input type="radio" name="" value="">
                        <input type="radio" name="" value="">
                       
                        <input type="submit" value="submit">
                    </div> -->
                
            </form>
            <span id="nav-buttons">
                <button id="previous">previous</button>
                <button id="next">next</button>
            </span>

        </div>
        <div id="results" class="hidden">
            <h2>Results:</h2>
            <p></p>
        </div>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>

【问题讨论】:

    标签: javascript jquery css show-hide dynamic-html


    【解决方案1】:

    考虑为此使用 jQuery 库中的 next() 和 prev(),以及当前可见元素的类。例如,当前可见元素下面有class="visibleQuestion"

    $('#next').on('click', function(){
        var v = $(".visibleQuestion");
        v.next().addClass("visibleQuestion").show();
        v.removeClass("visibleQuestion").hide();
    });
    

    上面的伪代码,但可能会给你一些想法。

    这里有一个超级简单的例子:http://jsfiddle.net/fmj34ejg/

    【讨论】:

    • 谢谢,一旦我整理好动态添加和删除的类,这将非常有帮助。知道这是怎么回事吗?
    • @Goodword 不太确定。现在看。我用一个 jsfiddle 示例更新了我的答案,以显示我的想法。不确定我是否完全符合您的需求,现在我正在查看它。 :)
    • 谢谢。这肯定会有所帮助。我想我应该让我的问题更清楚一点
    【解决方案2】:

    一个选择类中的第一个元素,就像我在上面的 sn-p 中所做的那样。问题不在于类选择机制——而是生成问题的 javascript 函数中的一个错误。

    有一个错误阻止我选择类中的第一个元素。在本段后面的函数中,.wrap(wrapper) 调用将 div 中的“form”元素包装为 class="question"——而不是我想要的单个问题。

    function qToHTML(question) {
        var header = "<h2>" + question.topic + "</h2>";
        var qText = "<p>" + question.question + "</p>";
        var options = "";
        for (var i = 0; i < question.choices.length; i++) {
            options += "<input type='radio' name='" + question.topic + "' value ='" + question.choices[i] + "'>" + question.choices[i] + "<br>";
        }
        var wrapper = "<div class='question'></div>";
    
        var HTMLstring;
        HTMLstring = header + qText + options;
        $("form").append(HTMLstring).wrap(wrapper);
    }
    

    这里是修改后的函数:

    函数 qToHTML(问题) {

    var header = "<h2>" + question.topic + "</h2>";
    var qText = "<p>" + question.question + "</p>";
    var options = "";
    for (var i = 0; i < question.choices.length; i++) {
        options += "<input type='radio' name='" + question.topic + "' value ='" + question.choices[i] + "'>" + question.choices[i] + "<br>";
    }
    
    var HTMLstring;
    HTMLstring = header + qText + options;
    HTMLstring = "<div class='question hidden'>" + HTMLstring + "</div>";
    $("form").prepend(HTMLstring);
    

    }

    【讨论】:

      猜你喜欢
      • 2011-04-06
      • 2012-01-01
      • 1970-01-01
      • 2015-03-15
      • 2011-09-30
      • 1970-01-01
      • 2011-02-14
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多