$('img.product_image').attr('src').change(function() {
    alert($('img.product_image').attr('src'));
});
嗨,你好
我正在尝试编写一些代码,当src更改时会提醒img.product_image,但是当我运行我的页面并单击按钮更改图像src时,警报不会出现...我的语法错了吗?
这是图像:
<img class="product_image colorbox-1160" id="product_image_1160" alt="Black Onyx Ring" title="Black Onyx Ring" src="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring.jpg" width="400">
当我点击其中一个缩略图时,图像src会改变:
<div class="wpcart_gallery" style="text-align:center; padding-top:5px;">
    <a rev="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/DSC_0162.jpg" class="thickbox cboxElement" rel="Black Onyx Ring" href="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/DSC_0162.jpg" title="DSC_0162">
        <img width="50" height="50" src="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/DSC_0162-50x50.jpg" class="attachment-gold-thumbnails colorbox-1160 " alt="DSC_0162" title="DSC_0162">
    </a>
    <a rev="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring1.jpg" class="thickbox cboxElement" rel="Black Onyx Ring" href="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring1.jpg" title="Black Onyx Ring">
        <img width="50" height="50" src="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring1-50x50.jpg" class="attachment-gold-thumbnails colorbox-1160 " alt="Black Onyx Ring" title="Black Onyx Ring">
    </a>
    <a rev="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring.jpg" class="thickbox" rel="Black Onyx Ring" href="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring.jpg" title="Black Onyx Ring">
        <img width="50" height="50" src="https://www.taranmarlowjewelry.com/wp-content/uploads/2012/10/Black-Onyx-Ring-50x50.jpg" class="attachment-gold-thumbnails colorbox-1160 " alt="Black Onyx Ring" title="Black Onyx Ring">
    </a>
</div>
Mil*_*war 23
.load在这种情况下,您可以使用事件:
$('img.product_image').on('load', function () {
 alert($('img.product_image').attr('src'));
});
此代码应比使用“ load”的答案更可靠地工作:
// ensures this works for some older browsers
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
// the element you want to observe. change the selector to fit your use case
var img = document.querySelector('img.product_image')
new MutationObserver(function onSrcChange(){
  // src attribute just changed!!! put code here
  alert($('img.product_image').attr('src'))
})
  .observe(img,{attributes:true,attributeFilter:["src"]})
尽管使用“ load”事件的某些答案在大多数情况下都可以使用,但在“ src”完成下载后会触发load事件。如果下载需要一段时间,则该事件可能会延迟;如果下载出现问题,则该事件可能永远不会触发(如果映像超时或将src设置为不存在或无效的映像,例如空映像,则会发生这种情况字符串)。
不需要BTW jQuery,但是如果您真的想使用它,则可以像下面这样获取目标img元素:
var img = $('img.product_image').get(0)
| 归档时间: | 
 | 
| 查看次数: | 33335 次 | 
| 最近记录: |