开发者

Match part of img src when comes into dom and add a class to a <p> tag that matches - jquery

I've got an ajax loaded image gallery that loads an image to the dom and then removes it and loads in the next one and rotates in that way.

Next to where the image comes in i've got a list of static names (they're there on page load and don't do anything) for the images.

What i want to do is as the image is loaded into the dom, i want to match part of it's src attribute to the class / id / rel / whatever of the name in the list.

The desired result is that as the image displays, it's name gets underlined and then when it goes it's name is not un开发者_如何学Goderlined anymore as the next images name has now become underlined...

I'm having real trouble with this, if anyone can show me how to do this i would be really bloody grateful!

Thank you!


you can use jQuerys .load() method (more precisly, the load event for images like

$('#imageid').load(function(){
   // image was loaded
   var mySrc = $(this).attr('src');

   if(mySrc.indexOf('some_string_identifier') > -1){
      $(this).addClass('underline');
   }
});

you may also call .load() on the window object. That is fired when all images (as a side effect it waits for some other things like iframes too) are loaded.

$(window).load(function(){
});

And do your checking right there.


Without all complex Regex in the way you can use id/rel attributes as you suggested initially. With this method you would not be matching the images src tag but matching it's ID attribute.

Here are your descriptions

<p id="item_desc_5">Plane</p>
<p id="item_desc_6">Car</p>

Here is your CSS class for the underline

<style type="text/css">.underline { text-decoration: underline; }</style>

Here is an example forat of the ajax'ed in

<img src="somepath.jpg" id="item_image_6" />

When loading in your image and you can match that with jquery you can do

<script type="text/javascript">
    jQuery(document).ready(function($) {
        var myImage = $('#some_image');
        var title = $('#item_desc_' + myImage.attr('id').replace('item_image_', ''));
        title.addClass('underline');
    });
</script>

Now an image with id item_image_6 would match the p tag with item_desc_6

It was a little difficult for me to give you the exact answer because i couldn't see your code that was ajaxing in the content.


EDITED - I'd do something like this

$('#imageid').load(function(){
   // image was loaded
   part = /some regex/.exec($(this).attr('src'));
   if(part != null) $('p').filter('[src*="'+part+'"]').addClass('underline');
}).attr('src','new_src.jpg');

the /some regex/ should return the part you want to match

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜