更改 .each 函数中 SRC 的值



我正在尝试获取一个元素的值,然后使用.each()函数在同一父元素内的另一个元素中使用它。但是,这似乎不起作用。这是我使用的代码。请告诉我我哪里做错了。

.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>

我想做的是获取<p class="img">的html(其中包含图像的URL(,并在页面加载时更改<img class="thumbnail"> src

请帮忙

$(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 触发加载图像。这会给用户带来巨大的延迟。缩略图的加载速度会比大图像快,但至少会有损坏图像的闪烁。

小提琴

您的代码中有小的拼写错误。函数});的闭包就像倒})};;

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

$(document).ready(function() {
        $('.item').each(function() {
            $(this).find('.thumbnail').attr('src', $(this).find('.img').html());
        }); 
   });

拼写错误

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

工作代码是:

$(document).ready(function () {
    $('.item').each(function () {
        $(this).find('.thumbnail').attr('src',$(this).find('.img').html());         
    })
});

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

最新更新