这是我的代码,第一个选择器用于单击id为#的div,而内部选择器是具有“-#”id的内部div,我的问题是如何只显示当前的内部div,因为当前单击时,页面上的所有内部div都显示和隐藏。请注意,这些div是通过php生成的,因此它们的值从1开始增加。还有另一个问题,,编写要显示的内部div选择器,而不是使用.filter来显示和隐藏的更好的方法是什么? --我找不到一种方法来使用"this“作为内部选择器。
例如。当我单击一个ID为"1“的外部div时,"popup-1”的内部div应该显示,而不是所有其他div。
$('div').filter(function(){
return this.id.match(/^\d+$/);
}).click(function() {
if($('div').filter(function () {
return this.id.match(/popup-\d+$/);
}).css('display') == 'none'
) {
$('div').filter(function () {
return this.id.match(/popup-\d+$/);
}).show();
} else {
$('div').filter(function () {
return this.id.match(/popup-\d+$/);
}).hide();
};
});<div class="test-style" id="1">
<div class="inner-test" id="popup-1" style="display: none">
</div>
</div>
<div class="test-style" id="2">
<div class="inner-test" id="popup-2" style="display: none">
</div>
</div>发布于 2015-04-19 07:41:20
使用类而不是对ID进行过滤,然后您需要获取您单击的元素的ID,并将其与popup-前缀连接,以获得要显示的元素的ID。
$(".test-style").click(function() {
var id = this.id;
$(".inner-test").hide();
$("#popup-" + id).show();
});.test-style {
height: 100px;
width: 100px;
background-color: red;
border: solid 1px black;
}
.inner-test {
height: 50px;
width: 50px;
background-color: blue;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test-style" id="1">
<div class="inner-test" id="popup-1" style="display: none">
</div>
</div>
<div class="test-style" id="2">
<div class="inner-test" id="popup-2" style="display: none">
</div>
</div>
但是,由于您想要显示的DIV总是在您单击的DIV中,所以您甚至不需要ID。只要做:
$(".test-style").click(function() {
$(".inner-test").hide();
$(this).find(".inner-test").show();
});发布于 2015-04-19 07:42:58
你的过滤器
this.id.match(/popup-\d+$/)由于通用'div'选择器,因此匹配文档中的所有内部元素。
而不是
if($('div').filter(function () {试一试
if($(this).filter(function () {只对单击元素的子元素进行筛选。
https://stackoverflow.com/questions/29726969
复制相似问题