我正在尝试使用菜单显示和隐藏图像。我怎样才能让它在开始时不显示任何内容,然后在点击时显示?
fiddle :http://jsfiddle.net/J3kjD/1/
我有这个 HTML:
<div id="media" class="col-5">
<img class="something" src="http://lorempixel.com/400/200/">
<img class="somethingelse" src="http://lorempixel.com/400/200/">
</div>
<button data-id="something" class="test">Click!</button>
<button data-id="somethingelse" class="test">Click!</button>
CSS:
#media > img {
display: none;
}
J查询:
$(document).on('click', '.test', function (e) {
category = $(this).data('id');
$('#media > img').css('display', 'none');
$('#media > .' + category).css('display', 'block');
});
最佳答案
您的问题是您为按钮分配了多个类名,而您只需要取第一个。
尝试:
$(document).on('click', '.test', function (e) {
var category = "." + this.className.split(" ").shift(), $media = $('#media'); //Get the first class name from the class names of the element
$media.children('img').css('display', 'none');
//You can use $media.children('img').hide()
$media.children(category).css('display', 'block');
//You can use $media.children(category).show()
});
关于jquery - 使用 jquery 显示/隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393837/