jquery为query.map设置一个click语句而不是3

时间:2013-08-15 19:16:51

标签: jquery

我有几个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”制作一个版本。你怎么改变它,所以你只需要写一次?

感谢您提供任何帮助。

2 个答案:

答案 0 :(得分:0)

此解决方案正确使用data-html 5属性。如果hte浏览器客户端不支持它,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!");
    }
  }

});

答案 1 :(得分:0)

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

$('.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