jQuery编写一个click语句来设置query.map而不是3 [英] jquery writing one click statement for query.map set up instead of 3

查看:103
本文介绍了jQuery编写一个click语句来设置query.map而不是3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个div设置如下:

I have several divs set up like so:

<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()的真实答案:

I'm adding up the true answers with jQuery.map() like so:

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

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

What I'm trying to do is write a super concise function for the click. If I were to write it out for each one I'd do:

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"制作一个版本.您将如何更改它,这样您只需要编写一次即可?

The problem with writing it like this is I'd have to make a version of it for each "answers_total". How would you change this so you only had to write it once?

感谢您对此的任何帮助.

Thanks for any help I can get on this.

推荐答案

因此,我假设当您在div中单击所有data-answer=true后,您想做些什么-您实际上不需要真正答案的数组然后您可以对每次点击进行检查

So I'm assuming you want to do something when all data-answer=true have been clicked inside the div - You really don't need the array of true answers then as you can do a check on each click

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

这篇关于jQuery编写一个click语句来设置query.map而不是3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆