gpt4 book ai didi

jquery if 语句隐藏元素

转载 作者:行者123 更新时间:2023-12-01 01:02:56 25 4
gpt4 key购买 nike

我似乎不知道如何简单地在第一个 div 上隐藏“上一个”按钮,在最后一个 div 上隐藏“下一个”按钮 .

希望有专业人士愿意帮助新手。这是我的代码:

<!DOCTYPE html>
<html>
<head>
<style>
div { width:40px; height:40px; margin:10px; float:left; border:2px blue solid; padding:2px; }
span { font-size:14px; }
p { clear:left; margin:10px; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div id="start"></div>
<div></div>
<p><button id="prev">Prev</button></p>
<p><button id="next">Next</button></p>
<script type="text/javascript">
var $curr = $("#start");
$curr.css("background", "#f99");
$("#prev").click(function () {
$curr = $curr.prev();
$("div").css("background", "");
$curr.css("background", "#f99");
});
var $curr = $("#start");
$curr.css("background", "#f99");
$("#next").click(function () {
$curr = $curr.next();
$("div").css("background", "");
$curr.css("background", "#f99");
});
</script>
</body>
</html>

最佳答案

我对您的标记进行了轻微修改,该修改反射(reflect)了解决此类问题的传统方法。

<div class="boxes">
<div>F</div>
<div>E</div>
<div>W</div>
<div class="active">L</div>
<div>X</div>
</div>
<p><button id="prev">Prev</button></p>
<p><button id="next">Next</button></p>​

请注意所有 div 元素周围的容器 .boxes。此外,请注意,我们不再使用 id,而是使用一个类 (.active) 来跟踪我们当前的位置。

// When the #prev or #next buttons within a p are clicked
$("p").on("click", "#prev, #next", function(e){
// Find reference to current active element, and remove class
var active = $(".active").removeClass("active");
// If we have an active element
active.length
// Determine direction of action
? $(this).prop("id") === "prev"
// If the #prev button was clicked, move back a sibling
? active.prev().addClass("active")
// If the #next button was clicked, move forward a sibling
: active.next().addClass("active")
// No active element? Set the first child as active
: $(".boxes :first-child").addClass("active");
// Show or hide #prev and #next based on active element location
$("#prev").toggle( !$(".active").is(":first-child") );
$("#next").toggle( !$(".active").is(":last-child") );
// Trigger this on load to setup active element if not already present
}).find("#prev").trigger("click");

fiddle :http://jsfiddle.net/txpj2/2/

关于jquery if 语句隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10678069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com