开发者

jQuery replace attribute within tag in known class id

How do you replace an attribute within a specific tag in a known class/id?

example, replace the src in img with a different file:

<div class="apple" id="poisoned">
<img border="0" width="25" hei开发者_如何转开发ght="25" src="default.png"></div>

But there are also other elements with the same id...

<div class="pear" id="poisoned"><img border="0" width="25" height="25" src="default.png"></div>

Suppose you just want to update the image in apple, how do you select it using jQuery?

Here's my try so far (*Edit - works)

$(".apple[id=poisoned] img").attr('src','replaced.png'); // not working
  • Edit - There are multiple apples and pears and other fruits on the page... Each poisoned fruit acts similarly, though not all should be poisoned at the same time! (Multiple will eventually be poisoned as they're clicked...) There is only one poisoned fruit per fruit type! (e.g. only 1 poisoned apple, only 1 poisoned pear, etc.)
  • Edit 2 - Actually, my try above works... Code error was in something else >.>


If I'm understanding you correctly,

$('#poisoned img').attr('src', 'newimage.png');

If you'd prefer to select by class,

$('.apple img').attr('src', 'newimage.png');

but I think you have your class and ID confused. IDs are supposed to always unique, whereas classes are not; you seem to be implementing them the other way around.


Something like:

$("div#poisoned img").attr('src','newimage.png')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜