繁体   English   中英

如果元素具有两个特定的类,请禁用按钮

[英]If element has two specific classes, disable button

我有一组div,用户可以通过单击下一个和上一个按钮来滚动。 在任何时候,仅应加载十个div。 当用户单击下一个按钮时,第一个div隐藏,并显示下一个div。 转到上一个按钮。 当用户正在查看第一个div时,我希望禁用上一个按钮;当用户正在查看最后一个div时,我希望禁用下一个按钮。 到目前为止,除了禁用按钮之外,我一切正常。

这是我的HTML的松散结构

<div>
    <button id="logo-previous"></button>
    <div class="logo-image"></div>
    <div class="logo-image"></div>
    <div class="logo-image"></div>
    <button id="logo-next"></button>
</div>

到目前为止,这是我的jQuery脚本:

$(document).ready(function() {
    $('.logo-image:lt(10)').show();
    $('.logo-image').first().attr('id', 'first');
    $('.logo-image').last().attr('id', 'last');
    $('.logo-image:lt(10)').addClass("current");

    $('#logo-next').click(function() {
        $('.current').first().removeClass("current").hide();
        $('.current').last().next().addClass("current").show();
    });

    $('#logo-previous').click(function() {
        $('.current').last().removeClass("current").hide();
        $('.current').first().prev().addClass("current").show();
    });
});

似乎禁用按钮的最简单方法是执行以下操作:

if (.logo-image).hasClass(current) && (.logo-image).hasClass(first) 
    (logo-previous).attr(disabled true)

由于某种原因,这种方法对我不起作用。 是否有更好的方法来禁用按钮?

使用选择器查找具有ID和类的元素。

$("#logo-previous").prop("disabled", $("#first.current").length != 0);

$("#logo-next").prop("disabled", $("#last.current").length != 0);

首先,您可以缩小代码范围

$(".logo-previous").attr("disabled", $(".logo-image").is(".first.current"));

或者您可以使用同级选择器:

$(".logo-image.first.current ~ .logo-previous").attr("disabled", true);

其次,可以通过将CSS3属性的指针事件设置为none来使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM