我需要你的帮助,
虽然下面的代码非常适合动态切换我的div内容,但现在的问题是javascript代码不会隐藏用户之前的选择。有关如何修改代码以动态切换div内容并隐藏用户先前选择的任何想法?
这是HTML和Javascript:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
window.onload = function() {
$("li").click(function(){
var $li = $(this);
var selector = $li.data("show"); // => "#item1"
$(selector).removeClass("hidden"); //but show matching item
});
}
</script>
<style type="text/css">
#container {
bottom: 0; left: 0; top: 0; right: 0;
margin: auto;
position: absolute;
width: 900px;
height: 600px;
}
#list {
list-style-type: none;
padding: 0;
margin: 0;
}
#list li {
margin:0 0 10px 0;
background: grey;
padding: 3px;
cursor: pointer;
}
.item {
width: 100%;
height: 100%;
background: rgb(192,192,192);
}
#menu {
float: left;
width: 25%;
background-color: #ff99CC;
height: 100%;
}
#content {
float: left;
width: 75%;
background-color: rgb(192,192,192);
height: 100%;
}
.hidden{ display:none; }
</style>
</head>
<body>
<div id="container">
<div id="menu">
<ul id="list">
<li data-show="#item1">Coffee</li>
<li data-show="#item2">Tea</li>
<li data-show="#item3">Ice Cream</li>
</ul>
</div>
<div id="content">
<div id="item1" class="hidden item">Something about coffee...</div>
<div id="item2" class="hidden item">Things about tea...</div>
<div id="item3" class="hidden item">Things about ice cream...</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
使用此:https://jsfiddle.net/mig1098/2xr1zy2b/
$("li").click(function(){
var $li = $(this);
var selector = $li.data("show"); // => "#item1"
$('.item').addClass('hidden');
$(selector).removeClass("hidden"); //but show matching item
});
您也可以使用过滤器验证id
值https://jsfiddle.net/mig1098/2xr1zy2b/1/
$("li").click(function(){
var $li = $(this);
var selector = $li.data("show"); // => "#item1"
$(selector).removeClass("hidden"); //but show matching item
$('.item').filter(function(){
return selector.indexOf($(this).attr('id')) > -1 ? false : true;
}).addClass('hidden');
});