开发者

Using JQuery to replace multiple instances of HTML on one page

I've made a script which copies the alt attribute of an image and puts it into a <span>. It also formulates the information divided by a hyphen. It works like a charm, but only with one image.

I would also like to wrap a <div> around the image to prevent unnecessary markup.

Script snippets:

HTML:

<div id="hoejre">
    <p>
         <span class="alignright">
             <img src="tommy_stor.jpg" alt="Name - Title" 
                  width="162" height="219" />
             <span></span>
         </span>
   </p>
</div>

jQuery:

var alt = $("#hoejre p span img").attr("alt");
$('#hoejre p span span')
 .html("<strong>" + alt.replace("-", "</strong> <em>") + "</em>");

Output:

<span class="alignright">
    <img height="219" width="162" al开发者_开发知识库t="Name - Title"                  
         src="tommy_stor.jpg">
        <span>
            <strong>Name</strong><em>Title</em>
        </span>
</span>

How do you I repeat the effect on several images, with different information within?


I would go for something like...

$(document).ready(function () {
  $('img.some-class').each(function () {
    var self = $(this);

    self.wrap('<div />').after('<span><strong>' + self.attr('alt').replace('-', '</strong> <em>') + '</em></span');
  });
});

Make sure that you assign a common class to those images you want this to work for, and alter "some-class" appropriately.

I wasn't so sure what 'unnecessary markup' you wanted removed, but the above code is a good starting point.


Here is another approach that assumes all the <img> elements are contained in a single element.

$('#box img').each(
  function(index,element){
    // do your magic here for
  }
)

The function inside jQuery.each() would be the same if you used this or Matt's approach. to expand Matt's approach to work with the HTML you provided:

$('span.alignright').each(
  function(index,element){
    var img=$(this).find('img');
    // do your magic here
  }
);

Which approach you take depends on your situation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜