This is a my jQuery and HTML code.
這是我的jQuery和HTML代碼。
my goal is when I click on the current box1, box2 or box3 , I want to display current sub box.
我的目標是當我點擊當前的box1, box2或者box3,我想顯示當前的子框。
For example : when I click on current box1 should be open current sub_box_1, and so. I did some jQuery code but I can't get result.
例如:當我點擊當前的box1時,應該打開當前的sub_box_1,這樣。我做了一些jQuery代碼,但無法得到結果。
Thanks!
謝謝!
$(document).ready(function() {
$('.sub_box').hide();
$('.box').click(function() {
$(this).$('#sub_box_1').show();
});
});
.box {
width: 150px;
height: 150px;
float: left;
margin-left: 20px;
border: 1px solid #333;
margin-top: 10px;
}
.sub_box {
width: 150px;
height: 150px;
border: 1px solid #09c;
}
Box 1
ADD
Box 2
ADD
Box 3
ADD
3 个解决方案
#1
3
Try using this:
試着用這個:
$(document).ready(function() {
$('.sub_box').hide();
$('.box').click(function() {
$(this).children('.sub_box').show();
});
});
jsfiddle示例:https://jsfiddle.net/d6zf0n1b/
#2
0
When you are using $(this).$('#sub_box_1'). you are trying to execute the $ function of the return of $(this). There is no $ function of $(this). Hence you are getting an error.
當您使用$(this).$('#sub_box_1')時。您正在嘗試執行$(此)返回的$函數。這里沒有$ $函數。因此,您將得到一個錯誤。
The other problem is that you are trying to access by the "#" accessor which matches the id not the class.
另一個問題是,您正在嘗試訪問“#”訪問器,該訪問器匹配的是id而不是類。
So this is why Andre's answer works. He is starting from the box that was clicked and looking for immediate children that have the class "sub_box".
這就是為什么安德烈的答案有效。他從被點擊的盒子開始尋找有類“sub_box”的直接子。
One thing to keep in mind is that the children method will only search one level down from the parent. If the box could be deeper down, you should use the 'find' method.
要記住的一點是,子方法只會從父進程中搜索一個級別。如果盒子可能更深處,你應該使用“查找”方法。
#3
0
You can use the jQuery find method (https://api.jquery.com/find/), which will find elements inside the the element matching the selector you use, try this:
您可以使用jQuery find方法(https://api.jquery.com/find/),它將找到與您使用的選擇器匹配的元素內的元素,請嘗試以下方法:
$(document).ready(function() {
$('.sub_box').hide();
$('.box').click(function() {
$(this).find('.sub_box').show();
});
});
.box {
width: 150px;
height: 150px;
float: left;
margin-left: 20px;
border: 1px solid #333;
margin-top: 10px;
}
.sub_box {
width: 150px;
height: 150px;
border: 1px solid #09c;
}
Box 1
ADD
Box 2
ADD
Box 3
ADD