gpt4 book ai didi

jquery - 为什么我的 jQuery 按钮在点击时不起作用?

转载 作者:行者123 更新时间:2023-12-01 07:55:07 25 4
gpt4 key购买 nike

我有一个无法正常工作的 JQuery 脚本。如果我将按钮元素放在 div 之外,那么它就可以工作。请帮我。谢谢。

http://jsfiddle.net/fysalyaqoob/6fornysr/8/

代码片段:

$('button').click(function() {
$(this).parent().find('.post').hide()
$('.' + this.id).show(500);
});

$('#showall').click(function() {
$('.post').show(500);
});
.post {
width: 100px;
height: 100px;
background: #555;
color: #fff;
float: left;
text-align: center;
margin-right: 10px;
margin-bottom: 10px;
padding: 20px;
}

.clearfix {
clear: both;
}

.wrapper {
margin: 20px 0;
background: #f3f3f3;
padding: 10px;
}


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
<div class="2">
<div class="wedding post">WEDDING DIL</div>
</div>
</div>
<div class="portrait post">PORTRAIT 1</div>
<div class="personal post">PERSONAL 1</div>
<div class="wedding post">WEDDING 2</div>
<div class="wedding post">WEDDING 3</div>
<div class="portrait post">PORTRAIT 2</div>

<div id="clear" class="clearfix"></div>

<div class="wrapper">
<div class="btn-group">
<button id="wedding">Wedding</button>
<button id="personal">Personal</button>
<button id="portrait">Portraits</button>
<button id="landscape">Landscape</button>
<button id="showall">Show All</button>
</div>
</div>

最佳答案

POST 元素不是按钮直接父元素的子元素。尝试用 parents 替换 parent

$('button').click(function() {
$(this).parents().find('.post').hide()
$('.' + this.id).show(500);
});

$('#showall').click(function() {
$('.post').show(500);
});

http://jsfiddle.net/6fornysr/13/

代码片段:

$('button').click(function() {
$(this).parents().find('.post').hide()
$('.' + this.id).show(500);
});

$('#showall').click(function() {
$('.post').show(500);
});
.post {
width: 100px;
height: 100px;
background: #555;
color: #fff;
float: left;
text-align: center;
margin-right: 10px;
margin-bottom: 10px;
padding: 20px;
}

.clearfix {
clear: both;
}

.wrapper {
margin: 20px 0;
background: #f3f3f3;
padding: 10px;
}


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
<div class="2">
<div class="wedding post">WEDDING DIL</div>
</div>
</div>
<div class="portrait post">PORTRAIT 1</div>
<div class="personal post">PERSONAL 1</div>
<div class="wedding post">WEDDING 2</div>
<div class="wedding post">WEDDING 3</div>
<div class="portrait post">PORTRAIT 2</div>

<div id="clear" class="clearfix"></div>

<div class="wrapper">
<div class="btn-group">
<button id="wedding">Wedding</button>
<button id="personal">Personal</button>
<button id="portrait">Portraits</button>
<button id="landscape">Landscape</button>
<button id="showall">Show All</button>
</div>
</div>

关于jquery - 为什么我的 jQuery 按钮在点击时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com