JQuery if set, or if it is not null?

I have the following jQuery code:

$("#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) {

    }

};

But this is a bit buggy. Is there an alternative that I can use to find out if this data attribute exists? Instead of usingif (url) { }

My HTML will be something like this:

<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>

Thus, not everyone will have all data attributes.


Edit: How to clear everything as soon as the space bar is pressed again?

For instance:

if (data.mobile) {

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

}

, icon mobile off. , , , , 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>
+5
2

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, delegate #menu 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');
}
+6

- :

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');

    }
});

, data-url.

+5

All Articles