首页 > 解决方案 > 更换

使用 jQuery 的带有图像的元素

问题描述

我很难使用 jquery 用图像替换字符串(URL)。我希望函数在页面加载时运行并用图像替换文本字符串。我需要它来处理包含在<event-description> <p>http://example.com/pageone.html </p> </event-description>on the page.这就是我所拥有的许多不同的“字符串”:

jQuery( document ).ready(function( $ ) {

       $('.event-description p').each(function () {

       string = $(this).text('http://example.com/pageone.html');
       $(this).html('<img width="75" src="https://example.com/images/logo-one.jpg" alt="' + string + '" />');

       string = $(this).text('http://example.com/pagetwo.html');
       $(this).html('<img width="75" src="https://example.com/images/logo-two.jpg" alt="' + string + '" />');

    });



});

任何帮助,将不胜感激!

标签: jqueryjquery-ui

解决方案


您必须使用条件来比较每个p.

jQuery( document ).ready(function( $ ) {

  $('.event-description p').each(function () {
    
    var string = $(this).text();
    
    if($(this).text() == 'http://example.com/pageone.html'){
      $(this).html('<img width="75" src="https://via.placeholder.com/75x75?text=1" alt="' + string + '" />');
    }

    if($(this).text() == 'http://example.com/pagetwo.html'){
    $(this).html('<img width="75" src="https://via.placeholder.com/75x75?text=2" alt="' + string + '" />');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="event-description">
  <p>http://example.com/pageone.html</p>
  <p>http://example.com/pagetwo.html</p>
</div>


推荐阅读