简体   繁体   English

.在javascript中查找背景图片

[英].find background-image in javascript

I am trying to optimize this code to find and replace the background image for the div class mp-e, but i'm struggling to figure out the right piece for the last line of the code.我正在尝试优化此代码以查找和替换 div 类 mp-e 的背景图像,但我正在努力为代码的最后一行找出正确的部分。 everything else is correct, it's just the .find function that i can't seem to figure out.其他一切都是正确的,只是我似乎无法弄清楚的 .find 函数。

HTML HTML

<center>
  <div class="mp-a"><div class="mp-b"><!-- |g_title| --></div></div>
  <div class="mp-h"> <!-- |posts| --> posts <i class="lar la-star"></i> <!-- |points| --> points</div>
  <div class="mp-c"><div class="mp-d">
  <div class="mp-e" style="background: url(<!-- |field_7| -->);">
    <div class="mp-f"><div class="mp-g">
     <!-- |awards| -->
    </div></div>
  </div>
  </div> </div>
  <a href="<!-- |field_22| -->"><div class="mp-i">Shipper</div></a>
  <a href="<!-- |field_23| -->"><div class="mp-i">Development</div></a>
  <a href="<!-- |field_25| -->"><div class="mp-i">Request</div></a>
</center>

Script脚本

<script>
  $('div[id*="pid_"]:contains([AI=)').each(function() {
    $(this).html($(this).html().replace(/ \[AI=(.+?)\]/i, '<span class="my_avatar" style="display: none">$1</span>'));
    var myAvatar = $(this).find('span.my_avatar').text();
    $(this).find('div.mp-e background image').attr('src', myAvatar);
  });
</script>

any insights would be great.任何见解都会很棒。 thank you!谢谢你!

CSS styles are not elements that you can find. CSS 样式不是您可以找到的元素。

You use the .css() method to change the style of an element.您可以使用.css()方法来更改元素的样式。

$(this).find('div.mp-e').css('background-image', `url(${myAvatar})`);

You placed backgroud and image as HTML elements while they are CSS attributes.您将backgroudimage作为 HTML 元素放置,而它们是 CSS 属性。

Try this, a bit different than yours试试这个,和你的有点不同

$(this).find('div.mp-e').css({
    "background": " url('YOUR IMAGE PATH')"
})

To add more CSS attributes add , to the object inside the .css function then enter your attribute : value要添加更多 CSS 属性,.css函数内的对象添加,然后输入您的属性:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM