jQuery If已设置,或者If不为null

jQuery If is set, or if is not null?

本文关键字:If 不为 null 或者 设置 jQuery      更新时间:2023-09-26

我有以下jQuery代码:

$("#menu span").click(function() {
    var url = this.getAttribute("data-url");
    var mobile = this.getAttribute("data-mobile");
    var facebook = this.getAttribute("data-facebook");
    if (url) {
    }
    if (mobile) {
    }
    if (facebook) {
    }
};

但它有点小故障。有没有其他方法可以用来查看此数据属性是否存在?代替使用if (url) { }

我的HTML将是这样的:

<ul>
    <li><span data-mobile="1" data-url="http://url.com">Site #1</span></li>
    <li><span data-url="http://site2.com" data-facebook="http://fblink">Site #2</span></li>
    <li><span data-url="http://site3.com">Site #3</span></li>
</ul>

因此,并不是每个人都拥有所有的数据属性。


编辑:再次单击跨度后,如何清除所有内容?

例如:

if (data.mobile) {
    $(".mobile").attr("data-link", data.mobile);
    $(".mobile").attr('class', 'icon mobile on');
}

因此,默认情况下,类是用icon mobile off加载的。然后,当单击跨度时,它会运行所有函数,如果它分配了mobile,那么它会将类转到icon mobile on,这非常适合第一个视图。但当我去另一个跨度时,它没有手机,它仍然保持以前的状态。如何在每次新点击时清除类似内容?

<div class="icons">
    <div class="icon website off" data-link=""></div>
    <div class="icon mobile off" data-link=""></div>
    <div class="icon fb off" data-link=""></div>
</div>

由于您使用的是data属性,因此可以使用jQuery data()方法来获取值并优化您的代码,如下图所示。

$("#menu span").click(function() {
    var data = $(this).data();//Will get all data attribute as key/value pairs
    if (data.url) {
    }
    if (data.mobile) {
    }
    if (data.facebook) {
    }
};

如果有多个span,则可以在#menu上使用delegate并查找span,这样click处理程序将仅在#menu元素上附加一次。试试这个。

$("#menu").delegate('span', 'click', function() {
    var data = $(this).data();//Will get all data attribute as key/value pairs
    if (data.url) {
    }
    if (data.mobile) {
    }
    if (data.facebook) {
    }
};

根据OP评论更新:

if (data.mobile) {
    $('.icons').attr("data-link", data.mobile)
    .removeClass('off').addClass('on');
}
else{
    $('.icons').removeAttr("data-link")
    .removeClass('on').addClass('off');
}

类似这样的东西:

var $spanObj = $("#menu span[data-url]").click(function() {
    var url = this.getAttribute("data-url");
    var mobile = this.getAttribute("data-mobile");
    var facebook = this.getAttribute("data-facebook");
    ...
    if (data.mobile) {
        $spanObj.filter('[data-mobile]').attr('class','icon mobile off');
        $(".mobile").attr("data-link", data.mobile);
        $(".mobile").attr('class', 'icon mobile on');
    }
});

仅选择包含要开始的数据url属性的跨度。