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

我有几个div设置如下:

SPEECH
RELIGION AND BELIEF
PRESS
ASSEMBLY
PETITION
SPEECH
RELIGION AND BELIEF
PRESS
ASSEMBLY
PETITION

我正在用jQuery.map()添加真正的答案,如下所示:

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

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

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

感谢您对我的任何帮助。

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

 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!"); } } }); 

所以我假设你想在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'); } } }); 

小提琴