简体   繁体   中英

Simple If statement for Javascript(jQuery)

I am trying to wrap my head around if statements. I am new to this.

I have a pretty simple script pulling data(text) from a html5 data attribute.

var $datatext = $(this).data('explain');

Now I want an if statement when html5 attribute data-explain is missing or empty.

var $success = if ($datatext < 0) {
    // show some other text, maybe? =
    $(this).text('Fail');
} else {
    // show original, maybe? =
    $(this).text($datatext);
}

Again, hard time wrapping my head around it. Ohhh these ifs.

You can do it this way,

Live Demo

$('.someclass').each(function() {    

    if(typeof this.attributes['data-explain']  != 'undefined')
    {
        alert(this.id + ": explain exists");
        explain = $.trim(this.getAttribute('data-explain'))
        if(explain.length > 0)
            alert(explain);
        else
            alert("no value for explain");
    }
    else
        alert(this.id + ": explain does not exists");
});​

check for the length not for the data in $datatext rewrite your code like this

if ($datatext.length > 0) {
    // show original, maybe? =
    $(this).text($datatext);

} else {
    // show some other text, maybe? =
    $(this).text('Fail');
}

That should work:

if (typeof $datatext !== 'undefined' && $datatext.length > 0) {
     $(this).text($datatext);
} else {
     $(this).text('Fail');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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