开发者

jQuery each() help

开发者 https://www.devze.com 2022-12-09 03:16 出处:网络
I have this structure <p class=\"descr\"> <span>something here</span> <img src=\"test\" />

I have this structure

<p class="descr">
  <span>something here</span>
  <img src="test" />
</p>

<p class="descr">
  <span>somthing else here</span>
  <img src="test2" />
  <img src="test3" />
</p>

so there c开发者_运维知识库an be more than one image inside of a <p> element.

What i need to do is loop through each <p> and then each <img> inside of it and add something to the front of it. Any help is appreciated. I tried doing an .each() but it's not working.


Try this:

$('p.descr > img').each(function() {
    // Make this code do what you want.
    $(this).prepend('<span>Prepended Content</span>');
});

The variable this represents the current image inside this function. In this example, I'm injecting a span element before each image inside a paragraph, but only direct descendant images.

This function can be shortened if you're only going to add another element before each image:

$('p.descr > img').prepend('<span>Prepended Content</span>');


$('p').each(function()
{
    $(this).find('img').each(function()
    {
        // do stuff with the image
    });
});


$('p.desc img').before('<span>here comes an image</span>');


$('p img').each(
  function(k, v)
  {
    $($(v).parents()[0] + 'span').html('Your text here');
  }
);

Manual


Something like this should do the trick:

$('p.descr img').before('<span>New Stuff</span>');


p = $('#p img');
p.each( function(i, val) { 
    $(val.id).append("<strong>Hello</strong>");
});
0

精彩评论

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

关注公众号