jQuery在Click上显示多个元素 [英] Jquery show multiple elements on Click

查看:87
本文介绍了jQuery在Click上显示多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

两列包含信息,一列包含问题,一列包含 answers .我想单击一个问题,然后在下一列中显示答案.该问题可以有多个答案,因此我需要单击一下以显示多个元素.

Two columns with information one with questions and one with answers. I want to click in one question and show in the next column the answer. The question can have multiple answers so I need to show multiple elements with a single click.

我写了一些代码,并用data attribute赋值:

I wrote some code taking a value with some data attribute like this:

HTML

<div class="evidence">
    <div data-answer=".A,.B">1</div>
    <div data-answer=".B,.C">2</div>
    <div data-answer=".A,.C">3</div>
</div>
<div class="answer">
    <div class="A">A</div>
    <div class="B">B</div>
    <div class="C">C</div>
</div>

jQuery

$(document).ready(function(){
    $('.evidence').on('click','div',function(){
        $('.answer div').hide();
        var ans = $(this).data('answer');
        $(ans).show();
    })
})

这是演示小提琴.

它可以工作,但是我的问题是是否有某种方法可以改进我的代码,避免在答案列中写入每个类名,而可能使用eq()或更有效的方式来显示元素.

It works but my question is if there is some way to improve my code avoiding write each classname in the answer column maybe showing the elements with eq() or some more efficient way.

谢谢

推荐答案

这是存储答案的另一种方法.您将答案的所有索引(是的,因为它以1开头,但我找不到更好的词)存储在数组中,并将它们分配给证据索引.

This is another way to store the answers. You store all the indexes (yeah I know, not really index since it starts with 1 but I couldn't find a better word) of the answers in an array and assign them to the index of the evidence.

var answers = {
    1: [1, 2, 3],
    2: [2, 3],
    3: [1, 3]
};

$('.evidence').on('click', 'div', function () {
    var ans = $(this).index() + 1;
    $('.answer div').hide().filter(function () {
        return answers[ans].indexOf($(this).index() + 1) > -1;
    }).show();
});

.evidence {
    width:200px;
    float:left;
}
.answer {
    width:200px;
    float:right;
}
.evidence div, .answer div {
    height:100px;
    line-height:100px;
    margin-bottom:15px;
    background:red;
    color:white;
    text-align:Center;
}
.answer div {
    background:orange;
    display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="evidence">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>
<div class="answer">
    <div>A</div>
    <div>B</div>
    <div>C</div>
</div>

还有一个玩弄代码 http://jsfiddle.net/g9hL881L/1/

这篇关于jQuery在Click上显示多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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