我试图在jquery中创建一个函数。我有三个有三个按钮的盒子。当我点击一个按钮,然后一个盒子会显示,其他的盒子将被隐藏。另一个按钮也是一样的。
$("#one").click(function () {
$(".box1").show();
$(".box2").hide();
$(".box3").hide();
});
$("#two").click(function () {
$(".box2").show();
$(".box1").hide();
$(".box3").hide();
});
$("#three").click(function () {
$(".box3").show();
$(".box1").hide();
$(".box2").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1" style="display:none">box one</div>
<div class="box2" style="display:none">box Two</div>
<div class="box3" style="display:none">box Three</div>
<button id="one" type="button">One</button>
<button id="two" type="button">Two</button>
<button id="three" type="button">Three</button>
我的问题是,是否有任何方法可以实现我的目标,而不重复相同的代码多次。
发布于 2021-05-27 12:55:06
有一种更简单的方法,您可以使用属性。
看看下面。
$(".container button").click(function(){
var className = "."+ $(this).attr("target");
$(".container div").hide() // hide all divs
// now view the target one
$(className).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box1" style="display:none">box one</div>
<div class="box2" style="display:none">box Two</div>
<div class="box3" style="display:none">box Three</div>
<button id="one" target="box1" type="button">One</button>
<button id="two" target="box2" type="button">Two</button>
<button id="three" target="box3" type="button">Three</button>
</div>
发布于 2021-05-27 12:58:07
下面是一种利用按钮的ID和div的ID来创建动态函数的方法
$(".button").click(function(e) {
// set up the object to map stuff
let obj = {
'one': 'box1',
'two': 'box2',
'three': 'box3'
};
$(".box").hide();
$("." + obj[e.target.id]).show();
});
.box {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1 box">box one</div>
<div class="box2 box">box Two</div>
<div class="box3 box">box Three</div>
<button id="one" class='button' type="button">One</button>
<button id="two" class='button' type="button">Two</button>
<button id="three" class='button' type="button">Three</button>
发布于 2021-05-27 13:02:03
单击任何按钮时,隐藏所有消息。然后,只需显示其类中谁的索引与其组内按钮的索引相匹配的消息。
$("button").click(function (event) {
// Hide all the messages
$(".box").each(function(index, box){
$(box).hide();
});
// Show just the message that applies
$($(".box")[$("button").index(event.target)]).show();
});
.hidden { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box hidden">box One</div>
<div class="box hidden">box Two</div>
<div class="box hidden">box Three</div>
<button type="button">One</button>
<button type="button">Two</button>
<button type="button">Three</button>
https://stackoverflow.com/questions/67729789
复制相似问题