Javascript jquery背景图像url失败

Javascript jquery背景图像url失败,javascript,jquery,Javascript,Jquery,这不起作用 $("#news_all ul li").css("background", "transparent url('../images/01.png') no-repeat"); 但这是可行的 .news_all_item li { background: url("../images/01.png") no-repeat scroll 0 0 transparent; margin-bottom: 2%; } 我的html <div class="news_

这不起作用

$("#news_all ul li").css("background", "transparent url('../images/01.png') no-repeat");
但这是可行的

.news_all_item li {
    background: url("../images/01.png") no-repeat scroll 0 0 transparent;
    margin-bottom: 2%;
}
我的html

<div class="news_all_item" id="news_all">
  <ul>
   <li><div class="news_item">Lorem Ipsum is simply dummy text of the printing and typesettiLorem Ipsum is simply dummy text</div></li>
   <li><div class="news_item">Lorem Ipsum is simply dummy text of the printing and typesettiLorem Ipsum </div></li>
   <li><div class="news_item">Lorem Ipsum is simply dummy text of the printing and typesetti</div></li>
  </ul>
</div>

  • Lorem Ipsum只是印刷的虚拟文本,typesettiLorem Ipsum只是虚拟文本
  • Lorem Ipsum只是打印和打字的虚拟文本
  • Lorem Ipsum只是打印和排版的虚拟文本

使用背景图像而不是背景

$("#news_all ul li").css("background-image", "transparent url('../images/01.png') no-repeat");

属性键应该是
背景图像
,而不是
背景

当您试图设置背景时,可以通过类选择器“.news_all_item”而不是“#news_all_item”应用

试试这个

$( "ul#news_all> li" ).css("background", "transparent url('../images/01.png') no-repeat");

路径可能会有问题。(如果可以,请给出绝对路径,即
资产/style/images/01.png

在css文件
。/images/01.png
中可能存在,但在js文件
。/images/01.png
中可能不存在

您可能有一个文件夹结构,如

asset
     |-->style
          |-->css
               |-->mycss.css
          |-->images
               |-->01.png
     |-->js
          |-->myjs.js

所以在这里,从css
。/images/01.png
是有效的,但是从js文件来看,同样的东西是无效的,我认为这是因为相对链接

我怀疑你的样式表可能在css文件夹中;javascript可能是用根文件夹中的html编写的

在样式表中,“./images/”是有效的,因为从文件夹css,“../”返回一级(到根文件夹),然后“/images”访问images文件夹。但是从根文件夹中,您必须省略../(不再需要返回一个级别)


无论如何,如果您使用的是相对链接,请记住路径的起点是编写代码的地方。

它们是两个不同的选择器?那是打字错误吗?此外,您在css中设置的选项比使用jquery设置时要多。我可以看到您的代码在这里工作得很好。您在控制台上看到任何错误吗?比如说404找不到图像?我想是的,bcoz我可以看到代码与有效路径一起工作,我也使用了这个$(“#news_all ul li:nth child(2)”).css('background-image','url('../images/01.png');
asset
     |-->style
          |-->css
               |-->mycss.css
          |-->images
               |-->01.png
     |-->js
          |-->myjs.js