我有以下内容,如果您单击其中一个列表项,将调用JavaScript函数。这应该运行下面的jQuery来隐藏/显示一个元素。
div#user-box
ul
li#dashboard(href="javascript:showonlyone('newboxes1')")
a Dashboard
li#settings(href="javascript:showonlyone('newboxes2')")
a Settings
div(class='newboxes' id='newboxes1')
p Dashboard
div(class='newboxes' id='newboxes2')
p Account ID:
我试过这个,但它没有工作:
$(document).ready(function() {
var showonlyone = function(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200)}
else {
$(this).hide(600);
}
})
}
})
功能必须正常工作,只是在点击列表项时不得调用该功能。
答案 0 :(得分:2)
我认为问题是函数超出了范围,如果你将函数移到$(document).ready
之外就可以了。
function showonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200)}
else {
$(this).hide(600);
}
})
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="user-box">
<ul>
<li id="dashboard">
<a href="#" onclick="showonlyone('newboxes1')">Dashboard</a>
</li>
<li id="settings">
<a href="#" onclick="showonlyone('newboxes2')">Settings</a>
</li>
</ul>
</div>
<div class="newboxes" id="newboxes1" hidden="hidden">
dashboard
</div>
<div class="newboxes" id="newboxes2" hidden="hidden">
settings
</div>
&#13;
答案 1 :(得分:0)
喜欢这个????
jQuery(document).ready(function (){
$('.newboxes').on('click', function(){
$('.div_newboxes').hide(600);
var div_id = "#div_" + $(this).prop('id');
$(div_id).show(200);
})
}(jQuery))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
<a class="newboxes" href="#" id="newboxes1">show this one only</a>
</div>
<div class ="div_newboxes" id="div_newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #1</div>
</td>
<td>
<div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
<a class="newboxes" href="#" id="newboxes2" >show this one only</a>
</div>
<div class ="div_newboxes" id="div_newboxes2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px; width: 150px;">Div #2</div>
</td>
<td>
<div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
<a class="newboxes" href="#" id="newboxes3" >show this one only</a>
</div>
<div class ="div_newboxes" id="div_newboxes3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px; width: 150px;">Div #3</div>
</td>
</tr>