我是 jQuery 的新手,编写了一些 jQuery 代码,以便在用户单击每个球队的球队 Logo 时显示每个足球队的信息。
我用过index()
确定哪个<div>
元素被单击。
我认为这一定是在不使用 index()
的情况下编写此代码的更好方法。为此,无需指定 <p>
具有类的元素 a,b and c
.
希望你能帮忙,这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
.w3-card{
width: 30%;
margin-right: 10px;
background-color: gainsboro;
cursor: pointer;
display: inline-block;
}
/*.w3-card:hover{*/
/*background-color: #B0B0B0;*/
/*}*/
p{
text-align: center;
font-family: Arial, sans-serif;
font-weight: bold;
}
img{
margin-left: auto;
margin-right: auto;
display: block;
}
.container{
width: 50%;
margin: auto;
}
.imgc{
margin-left: 20px;
margin-right: -20px;
}
.info{
width: 100%;
background-color: #82ABE5;
display: none;
padding: 5px;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
var a = "Juventus is one of the strongest team in Italy";
var b = "Barcelona is a spanish team";
var c = "Real madrid has the most awards in europe";
$('.w3-card').hover(function () {
$(this).css("background-color", "#B0B0B0");
},
function () {
$(this).css("background-color", "gainsboro");
});
$('.w3-card').click(function () {
var index = $(this).index();
$('.info').slideUp(400, function () {
$('p.a').hide();
$('p.b').hide();
$('p.c').hide();
if(index == 0){
$('.info').slideDown(400);
$('.a').show();
}
if(index == 1){
$('.info').slideDown(400);
$('.b').show();
}
if(index == 2){
$('.info').slideDown(400);
$('.c').show();
}
});
})
});
</script>
</head>
<body>
<div class="container">
<div class="imgc">
<div class="w3-panel w3-card"><img src="img/juve.png"><p>Juventus</p></div>
<div class="w3-panel w3-card"><img src="img/barca.png"><p>Barcelona</p></div>
<div class="w3-panel w3-card"><img src="img/real.png"><p>Real Madrid</p></div>
</div>
<div class="info">
<p class="a">Juventus Football Club colloquially known as Juve is a professional Italian association football club based in Turin, Piedmont.</p>
<p class="b">Futbol Club Barcelona commonly known as Barcelona and familiarly as Barça is a professional football club based in Barcelona, Catalonia, Spain.</p>
<p class="c">Real Madrid Club de Fútbol Royal Madrid Football Club), commonly known as Real Madrid, or simply as Real outside Spain frontiers, is a professional football club based in Madrid, Spain.</p>
</div>
</div>
</body>
</html>
最佳答案
一种方法是在可点击元素上添加自定义 data-*
属性。您已经在使用公共(public)类,因此这并没有太大变化:
<div class="w3-panel w3-card" data-target="a">
然后使用它:
$('.w3-card').click(function () {
var target = $(this).data("target");
$('.info').slideUp(400, function () {
$('.info').slideDown(400);
$('.' + target).show();
});
});
关于javascript - 尝试在 jQuery 中找到更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523697/