我试图一次显示一个div,所以当按下按钮时,它会显示div并隐藏其他div,如果其中任何一个可见。我尝试了一些例子,但都失败了。下面的代码只需点击一下即可隐藏所有显示的div。
<% for(var i = 0; i < 3; i++){ %>
<button class="but<%= i %>" >Show Skeetchpad</button>
<div id="p<%=i%>" ></div>
<script>
$(document).ready(function(){
$("#p<%= i %>").hide();
$(".but<%= i %>").click(function(){
if ($.trim($(this).text()) === 'Show Sketchpad') {
$(this).parent().siblings().hide();
$("#p<%= i%>").load("sketch.jsp");
$("#p<%= i %>").show("slow");
$(this).text('Hide Sketchpad').css("font-weight","bold");
} else {
$(this).text('Show Sketchpad').css("font-weight","normal");
location.reload(false);
$("#p<%= i %>").hide("slow");
}
return false;
});
});
</script>
<hr>
<%
}
%>
答案 0 :(得分:1)
$('button').on('click',function() {
var c = '.'+$(this).attr('class');
$('div').not(c).hide();
$(c).show();
})
&#13;
div {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="div1">div1</button>
<button class="div2">div2</button>
<button class="div3">div3</button>
<div class="div1">div1</div>
<div class="div2">div2</div>
<div class="div3">div3</div>
&#13;
答案 1 :(得分:0)
在按钮处理程序中添加以下代码段。
<%-- Get the class name of the button that is clicked --%>
var buttonClass = $(this).attr('class');
<%-- Get the div ID corresponding to the button clicked.
E.g. if the button clicked is but3, the corresponding div that needs to be shown
is p3. The remaining ones should be hidden
--%>
var divId = "p" + buttonClass[buttonClass.length - 1];
<%-- Hide all the divs the IDs of which start with a 'p' --%>
$("div[id^=p]").not(divId).hide();