0

我有几个像这样设置的div:

<div class="answers_total">
    <div data-answer="true" class="answer">SPEECH</div>
    <div data-answer="false" class="answer">RELIGION AND BELIEF</div>
    <div data-answer="true" class="answer">PRESS</div>
    <div data-answer="true" class="answer">ASSEMBLY</div>
    <div data-answer="false" class="answer">PETITION</div>
</div>
<div class="answers_total">
    <div data-answer="false" class="answer">SPEECH</div>
    <div data-answer="true" class="answer">RELIGION AND BELIEF</div>
    <div data-answer="false" class="answer">PRESS</div>
    <div data-answer="true" class="answer">ASSEMBLY</div>
    <div data-answer="false" class="answer">PETITION</div>
</div>

我正在用 jQuery.map() 像这样添加真正的答案:

var x = $('.answers_total').map(function(i,v){
    return $('div[data-answer=true]',v).length; // return how many have data-answer=true
});

我要做的是为点击编写一个超级简洁的函数。如果我要为每一个写出来,我会这样做:

var x = $(".answers_total").map(function(i,v) {
    return $('div[data-answer=true]',v).length;
});

clicks = 0;

$(".answer").click(function() {
    jthis = this;

    if ( $(jthis).att("data-attribute") == "true" ) {
        clicks++;
        if ( clicks == x[0] ) {
            alert('you found all the true answers');   
        }
    }
});

像这样写的问题是我必须为每个“answers_total”制作一个版本。你将如何改变它,所以你只需要写一次?

感谢您在这方面提供的任何帮助。

4

2 回答 2

0

所以我假设你想data-answer=true在 div 内点击所有内容时做某事 - 你真的不需要真正的答案数组,因为你可以在每次点击时进行检查

$('.answer').click(function(){
    var $el = $(this);
    if($el.data('answer')){ // if data-answer=true
        $el.attr('data-clicked','true'); // add data-clicked attribute to the data-true answer
        var totalClicked = $el.siblings('[data-clicked=true]').addBack().length; // total true elements clicked
        var totalTrueAnswer = $el.siblings('[data-answer=true]').addBack().length; // total available true elements
        if(totalClicked == totalTrueAnswer){ // if they equal
            alert('all found');
        }
    }
});

FIDDLE

于 2013-08-15T19:36:13.763 回答
0

此解决方案正确使用 data-html 5 属性。如果浏览器客户端不支持,jQuery 将包装 html 5 功能,否则它将允许客户端固有地处理“数据”处理。(快点)

var $answers = $(".answers_total");
//put the true answer count in a data block associated to the .answers_total element, + a click count
$answers.each(function(index,elem){
  $(this).data("trueCount", $('div[data-answer=true]',this).length);
  $(this).data("clicks",0);
});

$(".answer").click(function(event){
//if someone clicks, and the answer is true, process the click and store it in the parent .answers_total
  if($(this).data("answer") == true){
   var clicks = $(this).closest(".answers_total").data("clicks" ) +1;
    $(this).closest(".answer_total").data("clicks",clicks);
//check if all the true answers are found
    if(clicks >= $(this).closest(".answers_total").data("trueCount")){
      alert("you've found all the true answers!");
    }
  }

});
于 2013-08-15T19:29:33.657 回答