Javascript—根据元素的值设置元素的背景图像
此代码仅用于获取在线玩家数据:Javascript—根据元素的值设置元素的背景图像,javascript,ajax,Javascript,Ajax,此代码仅用于获取在线玩家数据: printf( "<div class=\"online\"><b class=\"Race\"> %s </b><b class=\"PlayerName\"> %s </b><b class=\"PPID\"> %s </b><br><li class=\"Class\"> %s </li><b class=\"Role\"> %
printf( "<div class=\"online\"><b class=\"Race\"> %s </b><b class=\"PlayerName\"> %s </b><b class=\"PPID\"> %s </b><br><li class=\"Class\"> %s </li><b class=\"Role\"> %s </b><b class=\"Gender\"> %s </b></div>",$row["Race"], $row["PlayerName"], $row["PPID"], $row["Class"], $row["Role"], $row["Gender"]);
printf(“%s%s%s
”%s %s%s“,$row[“Race”],$row[“PlayerName”],$row[“PPID”],$row[“class”],$row[“Role”],$row[“Gender”]);
^^^^^^^^^^^^^^^^
无需关注上述代码,结果如下:
从数据库获取上述代码时所需的结果:
我需要的是图像集
玩家名称:约翰
CLASS:WARRIOR尽管Javascript肯定不是完成这项工作的最佳工具,但您可以使用
innerHTML
属性来完成您想要的任务
document.getElementByClassName("Race").forEach(function(dom){
if(dom.innerHTML.indexOf('Human')>=0){
dom.style.backgroundImage = "url('human.png')";
}else if(dom.innerHTML.indexOf('Elf')>=0){
dom.style.backgroundImage = "url('elf.png')";
}
});
我坚持认为,您可以轻松地更改生成的HTML,然后使用非常快速和简单的CSS样式来完成这项工作:
<b class="Race Human"> Human </b>
<b class="Class Warrior "> Warrior </b>
<b class="Race Elf"> Elf </b>
<b class="Class Warrior "> Warrior </b>
.Race.Human{
background-image:url('human.png');
}
.Race.Elf{
background-image:url('elf.png');
}
人类
战士
精灵
战士
.种族{
背景图片:url('human.png');
}
.Race.Elf{
背景图片:url('elf.png');
}
请注意,CSS版本将不要求您在添加播放器或其他内容时重新运行脚本。而每次添加dom元素时都需要触发javascript版本。您没有显示足够的代码。。。让我们看看你到目前为止都做了些什么。我的猜测是,你只需要CSS。是的,但是通过javascript。让我再解释一下我需要什么。你能提供更多的DOM吗?也许是一个完整的class=“online”divcheck第一个代码,它的数据是使用ajax获取到主站点的,该站点有主体和其他元素。所以它的战士等等只有div online有玩家的在线数据。此外,onload功能将不起作用,因为将在线数据加载到页面需要2秒才能获得在线播放器
<b class="Race Human"> Human </b>
<b class="Class Warrior "> Warrior </b>
<b class="Race Elf"> Elf </b>
<b class="Class Warrior "> Warrior </b>
.Race.Human{
background-image:url('human.png');
}
.Race.Elf{
background-image:url('elf.png');
}