我正在制作一个显示人员个人资料的网站。每个人都被指定一个 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();
});
关于javascript - 如何创建变量来打开相同类型的div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26966833/