gpt4 book ai didi

javascript - jQuery 切换 3 Div

转载 作者:行者123 更新时间:2023-11-28 08:08:03 25 4
gpt4 key购买 nike

我想切换 3 div。在开始情况下,我有第一个 div,由于它的 ID,所以无法为 clic 触发。当我单击第二个或第三个 div(已触发)时,单击的 DIV 必须变得不可单击,而其他 2 个 div 可单击。

我附上我的实例:

http://jsfiddle.net/YV3V5/

HTML:

<div id = "not-selectable" class = "btn1">Div 1</div>
<div id = "selectable" class = "btn2">Div 2</div>
<div id = "selectable" class = "btn3">Div 3</div>

JavaScript:

$( "#selectable" ).click(function(e) {


var className = $(this).attr('class');

alert(className);

if (className == "btn1") {
$("btn1").attr("selectable","not-selectable");
$("btn2").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn2") {
$("btn2").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn3") {
$("btn3").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn2").attr("not-selectable","selectable");
}

});

在这种情况下,当我单击第二个 DIV 时,它应该变得不可单击......但什么也没有发生。

感谢您的帮助!

最佳答案

您的代码中有几个错误。最重要的是 ID 应该是唯一的。其次,您尝试为属性“可选择”和“不可选择”分配值。这些属性不存在。

如果您正确布置标记,则可以非常简单地完成此操作。我建议这样:

HTML

<div class="buttons">
<div class="button">Div 1</div>
<div class="button selectable">Div 2</div>
<div class="button selectable">Div 3</div>
</div>

jQuery

$( ".buttons" ).on("click",".selectable",function(e) {
$('.button').addClass('selectable');
$(this).removeClass('selectable');
});

<强> Can be tested here

(我添加了一个父元素来简化 jQuery 中的事件委托(delegate)。)

关于javascript - jQuery 切换 3 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24599644/

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