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

在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>'); 
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料