用js或jQuery根据下方的内容动态添加图片

因为我们的表格是后台渲染的,比如:判断内容为Windows时,给td标签添加一个<i class="windows_img"><i/>的标签;判断内容是Ubuntu时,给td标签添加一个<i class="Ubuntu_img"><i/>的标签。
我想要的最终代码格式是
<tr><td><i class="windows_img"></i>windows2007</td></tr>

//什么时候判断呢,是页面加载完吗?
$("#tableId td").each(function(k,ele){
    if($(this).html().indexOf("Windows") != -1){
        $(this).append('<i class="windows_img"><i>');
    }
   if($(this).html().indexOf("Ubuntu") != -1){
       $(this).append('<i class="Ubuntu_img"><i>');
   }
});

追问

您好,数据是后台获取的,想要获得数据是多少,应该只能页面加载完吧?

追答$("#tableId td").each(function(k,ele){
        var text = $(this).html();
    if(text .indexOf("Windows") != -1){
        $(this).html('<i class="windows_img"><i>'+text );
    }
   if(text .indexOf("Ubuntu") != -1){
       $(this).html('<i class="Ubuntu_img"><i>'+text );
   }
});

温馨提示:内容为网友见解,仅供参考
第1个回答  2016-07-13
<body><table id="tab"></table></body>
<script>
var tList= ['Windows','Ubuntu14.04','CentOS 7.2']; 
var htmlStr='';
$.each(tList,function(i){
    var type=
    tList[i].indexOf('Windows') >= 0 ?'Windows'//字符中如果包含windows
    : tList[i].indexOf('Ubuntu') >= 0 ?'Ubuntu'//字符中如果包含Ubuntu
    : tList[i].indexOf('CentOS') >= 0 ?'CentOS'//字符中如果包含CentOS
    : '';
    htmlStr+='<tr><td><i class="'+type+
             '_img"><i/></td><td>'+tList[i]+'</td></tr>';
}) 
$('#tab').append(htmlStr); 
</script>

追问

您好,您这个代码可以给我解释下么?我是个初学者,好多不太懂,而且我想要的代码格式是windows2008。大概就是这样

追答<body><table id="tab"></table></body>
<script>
//获取你的后台数据,我这里写死了一个数组
var tList= ['Windows','Ubuntu14.04','CentOS 7.2'];  
var htmlStr='';
//循环数组
$.each(tList,function(i){
  var type=
    tList[i].indexOf('Windows') >= 0 ? 'Windows' //字符中如果包含windows
  : tList[i].indexOf('Ubuntu')  >= 0 ? 'Ubuntu'  //字符中如果包含Ubuntu
  : tList[i].indexOf('CentOS')  >= 0 ? 'CentOS'  //字符中如果包含CentOS
  : '';
    //html代码拼接(已经改成你想要的效果)
    htmlStr+='<tr><td><i class="'+type+'_img"><i/>'+tList[i]+'</td></tr>';
}) 
$('#tab').append(htmlStr); //插入到table里
</script>

第2个回答  2016-07-13
加个判断,jquery选择器 添加不就好了.
你给的信息太少,原理很简单就是这样。
你要想要源码,复制过去就能用的,你得把你的页面代码贴出来。后台数据是什么样的。
第3个回答  2016-07-13
你在后台编写表格的时候,把图片判断显示上,这样更合理!
相似回答
大家正在搜