0

I am trying to get the values of an element and then use it in another element within the same parent element using .each() function. However, this seems not to work. Here are the codes I am using. Please tell me where I am doing wrong.

HTML:

<table>
    <tr class="item">
        <td>
            <img class="thumbnail" src="http://www.domain.com/images/image1.jpg">
        </td>
        <td>
            <p class="img">http://www.domain.com/images/image001.jpg</p>
        </td>
    </tr>
    <tr class="item">
        <td>
            <img class="thumbnail" src="http://www.domain.com/images/image2.jpg">
        </td>
        <td>
            <p class="img">http://www.domain.com/images/image002.jpg</p>
        </td>
    </tr>
</table>

JavaScript:

<script type="text/javascript">
    $(document).ready(function() {
        $('.item').each(function() {
            $(this).find('.thumbnail').attr('src', $(this).find('.img').html());
        )}; 
    )};
</script>

What I want to do is get the html of the <p class="img"> (which contains the url to an image) and change the src of <img class="thumbnail"> with that on page load.

Please help

4

5 回答 5

1

小提琴

您的代码中有小的拼写错误。函数的闭包});类似于)};倒置}

顺便说一下.prop,首选而不是.attr,您可以在此处阅读有关它的更多信息。

$(document).ready(function() {
        $('.item').each(function() {
            $(this).find('.thumbnail').attr('src', $(this).find('.img').html());
        }); 
   });
于 2013-07-05T11:13:45.567 回答
1
$(document).ready(function() {
     $('.item').each(function() {
         $(this).find('.thumbnail').prop('src', $(this).find('.img').html());
     }); 
});

最后你有)};而不是});. 此外,.prop首选.attr. 引用.prop文档

属性和属性之间的区别在特定情况下可能很重要。在 jQuery 1.6 之前,该.attr()方法有时会在检索某些属性时考虑属性值,这可能会导致不一致的行为。从 jQuery 1.6 开始,该 .prop()方法提供了一种在检索属性的同时显式检索属性值的方法.attr()


应该注意的是,在您的特定情况下,您是在页面加载和 jQuery 触发后加载图像。这会给用户带来巨大的延迟。缩略图会比大图像加载得更快,但至少会有一闪即逝的图像。

于 2013-07-05T11:15:43.060 回答
0

打字错误

<script type="text/javascript">
        $(document).ready(function () {
            $('.item').each(function () {
                $(this).find('.thumbnail').attr('src', $(this).find('.img').text());
            });
        });
    </script>
于 2013-07-05T11:20:31.667 回答
0

工作代码是:

$(document).ready(function () {
    $('.item').each(function () {
        $(this).find('.thumbnail').attr('src',$(this).find('.img').html());         
    })
});
于 2013-07-05T11:27:58.790 回答
0

jsfiddle的小错误检查,use }); instead of )};

于 2013-07-05T11:24:22.260 回答