普通网友 2018-11-25 18:35
浏览 425

在jQuery中使用If Else

Build an if else statement in my script.

If data = 0 I want to run return:

<i class="fa fa-check-circle"></i>

If data = 1 I want to run return:

<i class="fa fa-id-badge"></i>

If data = 2 I want to run return:

<i class="fa fa-quora"></i>

I have build a simple If Else statement so far. My script shows fa fa-check-circle when the returned data is 0 else it shows fa fa-id-badge.

Does someone know how I can make a definition for all the options. Something like:

(data == 0)
(data == 1)
(data == 2)

Here is my script:

<script type="text/javascript">
 $( document ).ready(function() {
  $('#grid1').DataTable({
   "bprocessing": true,
   "serverSide": true,
        "ajax": {
            "url": "response1.php",
            "type": "POST",
            "error": function(){
                $("#grid_processing").css("display","none");
            }
        },
       "columnDefs": [ 
            { "targets": 0, "render": 
            function ( data, type, full, meta ) { 
            return  '<i class="'+ (data == 0 ? 'fa fa-check-circle"></i>' :  'fa fa-id-badge"></i>'); 
            } } 
        ]    
  });   
 });
</script>
  • 写回答

3条回答 默认 最新

  • 乱世@小熊 2018-11-25 18:52
    关注

    This really only requires a basic if ... else statement instead of a ternary. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

    function ( data, type, full, meta ) { 
        var class;
        if (data == 0) {
            class = 'fa fa-check-circle';
        } else if (data == 1) {
            class = 'fa fa-id-badge';
        } else if (data == 2)) {
            class = 'fa fa-id-quora';
        }
        return  '<i class="' + class + '"></i>'); 
    }
    

    Of course you could continue to use a ternary but it's a bit ugly:

    function ( data, type, full, meta ) { 
        return  '<i class="fa ' + (data == 0 ? 'fa-check-circle' : (data == 1 ? 'fa-id-badge' : 'fa-quora')) + '"></i>'); 
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀