我想通过onclick事件调用一个函数来显示一个特定的div。有一次我只想显示一个div并且休息所有div不应该显示在我的网页中。我通过使用display css property尝试了这个。我只想要一个可以处理这个问题的函数。我可以通过创建多个函数来解决这个问题。
<html>
<head>
</head>
<body>
<ul>
<li><a href="#" onclick="someFunction();">1</a></li><!-- show div1-->
<li><a href="#" onclick="someFunction();">2</a></li><!-- show div2-->
<li><a href="#" onclick="someFunction();">3</a></li><!-- show div3-->
</ul>
<div id="first">content 1</div>
<div id="second">content2</div>
<div id="third">content3</div>
</body>
</html>
答案 0 :(得分:1)
这个怎么样:
请参阅以下更改:
<html>
<head>
</head>
<body>
<ul id="controls">
<li><a href="#" data-target="first">1</a></li><!-- show div1-->
<li><a href="#" data-target="second">2</a></li><!-- show div2-->
<li><a href="#" data-target="third">3</a></li><!-- show div3-->
</ul>
<div id="first" class="content">content 1</div>
<div id="second" class="content">content2</div>
<div id="third" class="content">content3</div>
<script>
$("#controls a").click(function() {
someFunction($(this).attr("data-target"));
});
function someFunction(divId) {
$(".content").hide();
$("#" + divId).show();
}
</script>
</body>
</html>
注意:您需要引用jQuery才能使$语法起作用。
答案 1 :(得分:0)
仅供参考,你可以用CSS做到这一点:
.panel {display: none}
.panel:target {display: block}
&#13;
<ul>
<li><a href="#first">1</a></li>
<li><a href="#second">2</a></li>
<li><a href="#third">3</a></li>
</ul>
<div class='panel' id="first">content 1</div>
<div class='panel' id="second">content2</div>
<div class='panel' id="third">content3</div>
&#13;
答案 2 :(得分:0)
我认为this就是你想要的:
<ul>
<li id="li_1"><a href="#first">1</a>
</li>
<li id="li_2"><a href="#second">2</a>
</li>
<li id="li_3"><a href="#third">3</a>
</li>
</ul>
<div class='panel' id="li_1_panel">content 1</div>
<div class='panel' id="li_2_panel">content2</div>
<div class='panel' id="li_3_panel">content3</div>
.panel {
display: none;
}
var panelID = "";
for (i = 1; i <= 3; i++) {
alert('#li_' + i);
$('#li_' + i).on('click', function () {
panelID = "#" + $(this).attr("id") + "_panel";
alert(panelID);
$(panelID).toggle();
});
}
修改强> 此外,如果您不想依赖严格的命名方案,则可以use a hash。
<ul>
<li id="zeus"><a href="#first">1</a>
</li>
<li id="athena"><a href="#second">2</a>
</li>
<li id="hades"><a href="#third">3</a>
</li>
</ul>
<div class='panel' id="isis">content 1</div>
<div class='panel' id="thor">content 2</div>
<div class='panel' id="aphrodite">content 3</div>
var panelID = "";
var li_to_panel = {
"zeus": "isis",
"athena": "thor",
"hades": "aphrodite"
};
$.each(li_to_panel, function(key, value){
alert(key);
liID = "#" + key;
$(liID).on('click', function () {
panelID = "#" + li_to_panel[$(this).attr('id')];
alert(panelID);
$(panelID).toggle();
});
});