замена <p>элементов изображением с помощью jQuery - PullRequest
0 голосов
/ 30 августа 2018

У меня возникают проблемы при замене строки (URL) изображением с помощью jquery. Я хочу, чтобы функция запускалась при загрузке страницы и заменяла текстовую строку изображением. Мне нужно, чтобы он работал со многими различными «строками», содержащимися в <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 + '" />');

    });



});

Любая помощь будет оценена!

Ответы [ 3 ]

0 голосов
/ 30 августа 2018

Это должно помочь вам. Просто имейте в виду, поскольку я использую одно и то же изображение в цикле, изображение будет одинаковым для всех элементов <p> . У вас может быть отображение объекта, указывающее на точное изображение, которое вам нужно, чтобы сделать его динамичным, или использовать атрибут data, который рекомендуется.

см. Ниже: <p data-imgurl='logo-one'>, data-imgurl - название изображения (логотипа) здесь

Примечание. Это добавляет изображение к имеющемуся тегу <p>. Если вы хотите удалить <p>, используйте $ (this) .parent (). Html (...)

$(function(){ //shorhand for document.ready function (same as yours)
    $('.event-description p').each(function () {
           var $this = $(this);
       
           //take the current string present in `<p>` tag
           var currentString = $this.text(); 
           //get data attribute to get the image name
           var imgUrl = $this.data('imgurl');
           
           $(this).html('<img width="75" src="https://example.com/images/'+imgUrl+'.jpg" alt="' + currentString + '" />');
           //replace with image tag with alt attribute as previous string
    }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event-description">
  <p data-imgurl='logo-one'>http://example.com/pageone.html</p>
</div>

<div class="event-description">
  <p data-imgurl='logo-two'>http://example.com/pagetwo.html</p>
</div>
0 голосов
/ 30 августа 2018

Вы можете использовать .replaceWith (функция)

$('.event-description p').replaceWith(function(idx, txt) {
  return $('<img/>', {width: "75", src: txt.trim(), alt: txt.trim()});
})
<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></div>
<div class="event-description"><p>http://example.com/pagetwo.html </p></div>
0 голосов
/ 30 августа 2018

Вы должны использовать условие для сравнения текста каждого 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...