我正在制作一个显示人物简介的网站。每个人都有一个svg按钮,单击该按钮时,将弹出一个窗口,显示该人的信息。

我有这个jQuery函数:

$('.button1').click(function() {
    $('.person1-profile').fadeIn();
});

$('.button1-exit').click(function() {
    $('.person1-profile').fadeOut();
});


$('.button2').click(function() {
    $('.person2-profile').fadeIn();
});

$('.button2-exit').click(function() {
    $('.person2-profile').fadeOut();
});


$('.button3').click(function() {
    $('.person3-profile').fadeIn();
});

$('.button3-exit').click(function() {
    $('.person3-profile').fadeOut();
});


我想知道是否有可能用Javascript做到这一点,从而大大缩短了编码,而不是每次都为每个人复制和粘贴该代码,如果可以为人员/个人资料创建变量,那将是一件事情喜欢:

$('var person + button').click(function() {
    $('var person + profile').fadeIn();
});

$('var button + exit').click(function() {
    $('var person + profile').fadeOut();
});


谢谢,我真的很感激!抱歉,如果不清楚。

最佳答案

您可以为此使用数据属性:

像这样定义您的按钮:

<button class="openButton" data-person="3">Open</button>
<button class="closeButton" data-person="3">Close</button>


像这样的打开/关闭代码:

$('.openButton').click(function() {
    var personNumber = $(this).attr("data-person");
    $('.person'+personNumber+"-profile").fadeIn();
});

$('.closeButton').click(function() {
    var personNumber = $(this).attr("data-person");
    $('.person'+personNumber+"-profile").fadeOut();
});


实际操作:http://jsfiddle.net/ndx4fn9n/

关于javascript - 如何创建变量以打开相同类型的div?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26966833/

10-09 08:16