javascript类在每次迭代中看到多个DOM?jquery.每个人都很困惑

javascript class sees multiple DOMs in each iteration? jquery .each getting confused

本文关键字:jquery DOM 每个人 迭代 javascript      更新时间:2023-09-26

我遇到了一个很奇怪的问题,我有一个简单的测试引擎,如果用户没有通过70%或更多的测试,它应该自己重新启动。

一切都很好,但当我重新初始化脚本时,在下一次迭代中,它似乎看到了更多次所有的questin-div。(和你失败的次数一样多)所以这让我一团糟,因为其他所有的计算都是基于这一点的。

以下是一切:http://jsfiddle.net/xdgrh/DhTQw/2/

如果你在第一个问题上选择B,在其他问题上选择任何其他选项,你可以复制这个问题。然后它会告诉你点击重启,因为你失败了。

在下一次迭代中,再次选择B并查看反馈。(我也检查了日志,它读取所有内容,就像每个问题都加倍一样。)等等,你做了多少次迭代,它计算了多少次

html在这里:(因为它必须按堆栈规则发布)

(焦点应在$('.btnNext')中。单击…并在$(".box:visible input:radio")中。each(function(index,value)。。。在那里,它数的是二三。。更多次。。取决于失败的次数)

<div id="lliquizContent">
<div id="headerX">
<h1>Task 1: Work with Today's Client (Final task) </h1>
</div>
<div class="feedback">
<div class="feedback-title">
FEEDBACK TITLE 
</div>
<div class="feedback-text">
FEEDBACK TEXT 
</div>
<img src="/Resource/GetResource/CRSTechModule1/feedback.m1s29.1.png" border="0" />
<div style="clear:both;"> </div>
<div class="feedback-footer">
<div class="btnFeedbackNext">Next Question ></div>
<div class="score"><strong>Score: &nbsp;&nbsp;</strong><span class="score"></span> %</div>
</div>
</div>
<div class="box" type="1">
<div class="headerX">
<p>Task question 1 of 4</p>
</div>
<div class="question qsize1">
<div class="questionText">Based on Anne’s original email, how should you respond?</div>
<div class="answerswers">
<table>
<tr>
<td><input type="radio" name="" value="0" /> </td>
<td><label>Email Anne to set up a face-to-face meeting.</label></td>
<td>
<feedback>
<fbtitle>Incorrect. You did not select the best approach for responding to Dr. Anne Jones. Click Next to view the next question.</fbtitle>
<fbtext>"I’d like to be able to meet with you, but as I said in my original email, I am just too busy! Please email me your thoughts about homes that might be suitable for my situation."</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="1" /> </td>
<td><label>Email Anne and ask her to register on your website.</label></td>
<td>
<feedback>
<fbtitle>Correct! You selected the best approach for responding to Dr. Anne Jones. Click Next to view the next question.</fbtitle>
<fbtext>"Thanks for getting back to me. I’ll look at the two homes you mentioned and try to register on your website when I get a chance. I am very excited about getting a new home in Springfield. Thanks for helping me."</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="0" /> </td>
<td><label>Email Anne to qualify her as a possible lead.</label></td>
<td>
<feedback>
<fbtitle>Incorrect. You did not select the best approach for responding to Dr. Anne Jones. Click Next to view the next question.</fbtitle>
<fbtext>"I really don’t have any more information to give you at this time. As I wrote in my original email, I think new construction would be ideal for me. Can’t you just email me information on homes that are available? I don’t have a lot of time."</fbtext>
</feedback>
</td>
</tr>
</table>
</div>
</div>
<div style="clear: both;"> </div>
<div class="attachments">
<a id="transcript-button1" href="#" lliQuizTitle="Transcript 1 lliQuizTitle">Approach #1</a> | 
<div style="display: none;" id="TRANSCRIPT-TEXT1" lliQuizTitle="Transcript 1 lliQuizTitle">transcript 1</div> 
<a id="transcript-button2" href="#">Approach #2</a> | 
<div style="display: none;" id="TRANSCRIPT-TEXT2" lliQuizTitle="Transcript 2 lliQuizTitle">transcript 2</div>
<a id="transcript-button3" href="#">Approach #3</a>
<div style="display: none;" id="TRANSCRIPT-TEXT3" lliQuizTitle="Transcript 3 lliQuizTitle">transcript 3</div>
</div>
<div class="btnContainer"><a class="btnNext">SUBMIT</a></div>
<div class="instructions">Select the correct answer then click the forward arrow to continue.</div>
<div class="rightAttachmentBox">
<a id="transcript-button4" href="#">Click here</a><br />
to see the email from<br /> 
Anne Jones
<div style="display: none;" id="TRANSCRIPT-TEXT4" lliQuizTitle="Transcript 4 lliQuizTitle" lliQuizTop="20" lliQuizLeft="200" lliQuizWidth="300" lliQuizHeight="300">
    transcript 4 transcript 4 transcript 4
</div>
</div>
</div>
<div class="box" type="2">
<div class="headerX">
<p>Task question 2 of 4</p>
<div class="questionText">Based on Anne’s original email, how should you respond?</div>
</div>
<div class="questions qsize2">
<table>
<tr>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answerswers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answerswers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
</tr>
<tr>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answerswers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answerswers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
</tr>
</table>
</div>
<feedback>
<correct>
<fbtitle>Correct...</fbtitle>
<fbtext>"Text..."</fbtext>
</correct>
<incorrect>
<fbtitle>Incorrect...</fbtitle>
<fbtext>"Text...."</fbtext>
</incorrect>
</feedback>
<div style="clear: both;"> </div>
<div class="btnContainer"><a class="btnNext">SUBMIT</a></div>
<div class="instructions">Select the correct answer then click the forward arrow to continue.</div>
</div>
<div class="box qsize3" type="3">
<div class="headerX">
<p>Task question 3 of 4</p>
<p>Select the best Target group for you based on your data. Next, select your Rationale and click Submit to get your feedback. You may view your client analysis at any time to help you choose an approach.</p>
<div class="questionText">I’ve reviewed your client analysis and I have an idea of where you might be able to add a lot of value to your clients. But I want to know what you think.<br />
What target group do you think it makes the most sense for you to select? Why?</div>
</div>
<div class="questions qsize3">
<table>
<tr valign="top" >
<td>
<div class="question">
    <div class="questionText">Target group</div>
    <div id="answerswers">
        <table>
            <tr>
                <td><input type="radio" name="" value="0" /></td>
                <td><label> Doctors and nurses transferring to Springfield.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>I think you should focus on transfers into Springfield, however, I think that group may be a little too specific.</fbtext>
                    </feedback>
                </td>
            </tr>
            <tr>
                <td><input type="radio" name="" value="0" /></td>
                <td><label>Home sellers with older homes looking to purchase new construction.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>I thought you didn’t like to work with this group.</fbtext>
                    </feedback>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="radio" name="" value="0" />
                </td>
                <td><label>Home buyers looking for older homes outside of Springfield.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>I am not sure why you picked this group. I thought you liked new construction.</fbtext>
                    </feedback>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="radio" name="" value="1" />
                </td>
                <td><label>First-time home buyers and transfers to the area looking for new construction.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext></fbtext>
                    </feedback>
                </td>
            </tr>
        </table>
    </div> 
</div>
</td>
<td>
<div class="question">
    <div class="questionText">Rationale</div>
    <div id="answerswers">
        <table>
            <tr>
                <td><input type="radio" name="" value="1" /></td>
                <td><label>I only want to focus on one specific group that is associated with the hospital.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>For the rest of this meeting, I think we should focus on first-time home buyers and transfers to the area looking for new construction.</fbtext>
                    </feedback>
                </td>
            </tr>
            <tr>
                <td><input type="radio" name="" value="0" /></td>
                <td><label>I don’t want to pick between two of the buyer types with whom I enjoy working.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>For the rest of this meeting, I think we should focus on first-time home buyers and transfers to the area looking for new construction.</fbtext>
                    </feedback>
                </td>
            </tr>
            <tr>
                <td><input type="radio" name="" value="0" /></td>
                <td><label>Older homes have a lot more character than new construction.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>For the rest of this meeting, I think we should focus on first-time home buyers and transfers to the area looking for new construction.</fbtext>
                    </feedback>
                </td>
            </tr>
            <tr>
                <td><input type="radio" name="" value="0" /></td>
                <td><label>Springfield is not expanding and there aren't new construction homes.</label></td>
                <td>
                    <feedback>
                        <fbtitle></fbtitle>
                        <fbtext>I agree that you should focus on first-time home buyers and transfers looking for new construction. But why did you select them?</fbtext>
                    </feedback>
                </td>
            </tr> 
        </table>
    </div> 
</div>
</td>
</tr>
</table>
</div>
<feedback>
<correct>
<fbtitle>Correct! You selected an appropriate target market and the best rationale. Click Next to view the next question.</fbtitle>
<fbtext>"I agree! I think you will be very happy working with this group and it sounds like you are well on your way to becoming a new construction expert. This expertise will add value to the service you provide your clients."</fbtext>
</correct>
<incorrect>
<fbtitle>You have a red X next to each incorrect answer. You did not select the best choices here. Click Next to view the next question.</fbtitle>
<fbtext></fbtext>
</incorrect>
</feedback>
<div style="clear: both;"> </div>
<div class="btnContainer"><a class="btnNext">SUBMIT</a></div>
<div class="instructions">Select the correct answer then click the forward arrow to continue.</div>
</div>
<div class="box-fail">
Ponovo init... <a href="#" id="initButton" onclick="">TRY AGAIN...MUST GET 70%+</a>
</div>
<div class="box-success">
It's on, go on...</div>
</div>

这是:

var lliQuiz = {
    message1: "message1",
    message2: "",
    feedbackImage: "/image/not/set",
    score: 0,
    currentTab: 0,
    checkFormat: function() {
        var $boxes = $('.box'), valid = $boxes.length > 0;
        if (valid) {$boxes.each(function (idx, box) {
                var $box = $(this),$qtns = $box.find('.question');
                if ($qtns.length == 0) {
                    valid = false; return false;
                } valid = $qtns.filter(function () {
                    return $(this).find('input[type="radio"]').length < 2;
                }).length == 0; if (!valid) { return; }
            })
        }
        if (valid) {return true;} else {return false;exit;}
    },
    createFeedback: function(boxVisible,type,farray,addScore) {
        $('.feedback img').attr('src',lliQuiz.feedbackImage);
        if (type == 1) {
            $.each(farray, function(i,id){ // NE TREBA FOR EACH??? samo je jedno pitanje...
                $('.feedback .feedback-title').text($('input[id='+id+']').nextInDOM('fbtitle').html());
                $('.feedback .feedback-text').text($('input[id='+id+']').nextInDOM('fbtext').html());
            });
        }
        if (type == 2) {
            if (addScore == true) {
              $('.feedback .feedback-title').text($(boxVisible).find('feedback > correct > fbtitle').html());
              $('.feedback .feedback-text').text($(boxVisible).find('feedback > correct > fbtext').html());
            } else {
              $('.feedback .feedback-title').text($(boxVisible).find('feedback > incorrect > fbtitle').html());
              $('.feedback .feedback-text').text($(boxVisible).find('feedback > incorrect > fbtext').html());
            }           
        }
        if (type == 3) {
            if (addScore == true) {
              $('.feedback .feedback-title').text($(boxVisible).find('feedback > correct > fbtitle').html());
              $('.feedback .feedback-text').text($(boxVisible).find('feedback > correct > fbtext').html());
            } else {
                var text = "";
                $.each(farray, function(i,id){
                    var br = (i == 0) ? "<br /><br />" : "";
                    text = text + " " + $('input[id='+id+']').nextInDOM('fbtext').html() + br;
                });
                $('.feedback .feedback-title').text($(boxVisible).find('feedback > incorrect > fbtitle').html());
                $('.feedback .feedback-text').html('"'+text+'"');
            }
        }
        return true; 
    },
    checkAnswers: function() { return 5; },
    init: function() {
        $('.box, .box-success, .box-fail').fadeOut(100);
        $('span.redx').remove();
        lliQuiz.score = 0;
        lliQuiz.currentTab = 0;
        console.log('init poeni: '+lliQuiz.score);
        // check format
        if (lliQuiz.checkFormat()) {
            $('.box:first').fadeIn(1000);
            console.log( "LLI - HTML FORMAT OK!!!" );
        } else {
            $('#lliquizContent').html('<div style="color: red; font-size: 16px; font-weight: bold; text-align: center; width: 100%;">HTML FORMAT ERROR</div>');
            console.log( "LLI - HTML FORMAT ERROR!!!" );
        }
        console.log( "LLI - Quiz Start!" );
        var pointsPerQuestion = parseFloat(100 / $('.box').length).toFixed(2);
        $(".question").each(function(index,value) {
            var groupNumber = ++index;
            $(":radio", this).attr("name", "group" + groupNumber).each(function(index,value){
                $(this).removeAttr('checked').attr("id","id"+groupNumber+index).nextInDOM('label').attr("for","id"+groupNumber+index);
            });
        });
        $('input').iCheck('uncheck'); 
        $('input').iCheck({ checkboxClass: 'icheckbox_minimal-blue', radioClass: 'iradio_flat-blue' });
        // lli idemo dalje...
        $('.btnNext').click(function(e) {
                e.preventDefault();
                var status = true;
                var addScore = false;
                var carray = []; carray.length = 0;
                var xarray = []; xarray.length = 0;
                var farray = []; farray.length = 0;
                lliQuiz.currentTab++;
                $('span.redx').remove();

                $(".box:visible input:radio").each(function(index, value){
                        if($("input:radio[name="+$(this).attr("name")+"]:checked").length == 0) {
                            status = false;
                        }
                        if(value.value == 1 && value.checked == true) {
                            carray.push($(this).attr("id"));
                            console.log($(this).attr("id"));
                        }
                        if (value.value == 0 && value.checked == true)  {
                            xarray.push($(this).attr("id"));
                            console.log($(this).attr("id"));
                        }
                        if (value.checked == true)  {
                            farray.push($(this).attr("id"));
                            console.log($(this).attr("id")); 
                        }
                });
            if (carray.length == $(".box:visible .question").length) {
                lliQuiz.score += parseInt(pointsPerQuestion);
                    if (lliQuiz.score == 99) $('span.score').text(100);
                    else
                    $('span.score').text(lliQuiz.score);
                addScore = true;
            } else {
                addScore = false;
                if (lliQuiz.score == 0) $('span.score').text(0);
            }
            if (status == false) {
            $("#lliquizContent").block({ message: lliQuiz.message1 , theme: false, timeout: 2500, fadeOut: 400, overlayCSS: {opacity: 0.1, cursor: "default"}, css: {border: '1px solid #333',width: '200px', padding: '10px','border-radius': '7px', color: 'red', '-webkit-border-radius': '7px', '-moz-border-radius': '7px' } });
                exit;
            } else {
                $("#lliquizContent").block({ message: false , theme: false, overlayCSS: {opacity: 0.1, cursor: "default"} });
                $.each(xarray, function(i,id){
                    $('#'+id).prevInDOM('.questionText').prepend('<span class="redx">X</span>');
                });
                lliQuiz.createFeedback($(".box:visible"),$('.box:visible').attr('type'),farray,addScore);
                $(".feedback").fadeIn(1000);    
            }
        });
        $('.btnFeedbackNext').click(function() {
            console.log('feedback poeni: '+lliQuiz.score);
            if ($('.box').length == lliQuiz.currentTab) {
                $('.feedback').fadeOut(200);
                $('#lliquizContent').unblock();
                $('.box:visible').fadeOut(200);
                if (lliQuiz.score >= 70) {
                    $('.box:visible').fadeOut(300);
                    $('.box-success').fadeIn(1000);
                    $.hurdleNext(false);
                } else {
                    $('.box-fail').fadeIn(1000);
                    $.hurdleNext(true);
                }
            } else {
                $('.feedback').fadeOut(300);
                $('#lliquizContent').unblock();
                $('.box:visible').fadeOut(function(){
                    $(this).next().fadeIn(1000);
                    return false;
                });
            }
        });
    },
    test: function() { alert('lli test'); }
}
    lliQuiz.message1 = "Please answer the questions before submiting!";
    lliQuiz.feedbackImage = "feedback.m1s29.1.png";
    lliQuiz.init();
    $('#initButton').click(function(){
        lliQuiz.score = 0;
        lliQuiz.init();
    });

单击#initButton时,将向按钮添加另一个单击事件处理程序。

在初始化之前,应该使用.unbind();来清除事件。

$('#initButton').click(function(){
    // remove click handler for elements
    // use .unbind('click'); specifically to remove click events
    $('.btnFeedbackNext').unbind('click');
    $('.btnNext').unbind('click');
    lliQuiz.score = 0;
    lliQuiz.init();
});

编辑:在jQuery的后续版本中,首选的方法是使用.off();

感谢@AnthonyGrist指出这一点:)

下面是一个示例Here