简单的If语句为Javascript(jQuery)

时间:2012-12-06 11:36:40

标签: javascript jquery if-statement

我试图在声明中包围我的头脑。我是新手。

我有一个非常简单的脚本从html5数据属性中提取数据(文本)。

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

现在,当html5属性data-explain丢失或为空时,我想要一个if语句。

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

再一次,很难把头缠绕在它周围。哦,这些ifs。

3 个答案:

答案 0 :(得分:0)

你可以这样做,

<强> 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");
});​

答案 1 :(得分:0)

检查$datatext中的数据的长度,而不是像这样重写代码

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

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

答案 2 :(得分:0)

这应该有效:

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