1

我试图绕过 if 语句。我是新来的。

我有一个非常简单的脚本从 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);
}

再一次,很难把我的头绕在它周围。哦,这些如果。

4

3 回答 3

0

你可以这样做,

现场演示

$('.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");
});​
于 2012-12-06T11:39:36.537 回答
0

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

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

} else {
    // show some other text, maybe? =
    $(this).text('Fail');
}
于 2012-12-06T11:41:32.403 回答
0

那应该工作:

if (typeof $datatext !== 'undefined' && $datatext.length > 0) {
     $(this).text($datatext);
} else {
     $(this).text('Fail');
}
于 2012-12-06T11:42:07.503 回答