开发者

How to reference an image inside another tag with 'this'?

I know this is pretty basic, I'm trying to get the 'src' attribute of some images and put them in the same number of #image fields:

        count = 0;
        $('.selected').each(function() {
            count++;
            // the idea is to get the value from each ".selecte开发者_开发百科d img"
            $('#image' + count).val(   this + img   ).attr("src");
        });

How to reference the image from 'this' ? or what would be the good method ? .... Thanks !

EDIT:

I have something like this:

        <li><img src="..." alt="" class="selected" /></li>
        <li><img src="..." alt="" /></li>
        <li><img src="..." alt="" /></li>
        <li><img src="..." alt="" class="selected" /></li>

I want to write the src attribute of those img s in this:

    <input type="hidden" id="image1" name="image1" value="" />                  
    <input type="hidden" id="image2" name="image2" value="" />  

Thanks!


Is this the sort of thing you mean?

$(function() {
    var count = 0;
    $('.selected').each(function() {
        count++;
        var source = $('img', this).attr('src');
        $('input#image' + count).val(source);
    });
});


$('img.selected').each(function(i, img) {
    $('#image' + (i + 1)).val(img.src);
});


If I understand what you're asking correctly, you'd like to put the src attribute in each associated hidden field tag, is that correct? I'm a little confused as to the distinction between the use of selected vs non-selected images, so I'm ignoring that in this solution:

HTML:

<ul>
    <li><img src="src0" alt="" class="selected" /></li>
    <li><img src="src1" alt="" /></li>
    <li><img src="src2" alt="" /></li>
    <li><img src="src3" alt="" class="selected" /></li>
</ul>

<input type="text" id="image0" name="image0" value="" />                  
<input type="text" id="image1" name="image1" value="" />  
<input type="text" id="image2" name="image2" value="" />  
<input type="text" id="image3" name="image3" value="" />  

Script:

$('input[type=text]').each(function(idx, e){
    $(this).val($($('img')[idx]).attr('src'));
});

http://jsfiddle.net/dbrecht/MDfD9/

(I used text fields here for illustration, but you could change the attributes to hidden easily)

Of course, this assumes that each image has an associated input field. I'm a little curious as to why you're going down this path though.. What exactly are you trying to accomplish? From what I've seen, there may be other ways of going about it..


I think this is what you mean.

    $('.selected').each(function(idx, obj) {
        $('#image' + (idx + 1)).attr("src", obj.src);
    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜