1

如何编写 jQuery 代码来说明“如果 'page.php' 存在于 img src 中,则不要在该 img 上运行 'example function'。如果 'page.php' 不存在于 img src 中,则在该图像上运行“示例函数”。”?

该页面将有多个图像,并且并非所有图像都在图像 src 中具有“page.php”。

这是我到目前为止尝试过的代码,但没有成功:

<script type="text/javascript">
if (jQuery('img').attr('src').indexOf('page.php') >= 0) {
    example();
}
</script>

编辑#1:

以下是我的完整脚本。基本上,我不想在 src URL 中已经包含“phpThumb.php”的图像上运行此脚本。

var ssWidth = 0;
var ssSrc;
var ssImg;
var ssc;
jQuery(document).ready(function(){
    ssc = jQuery('#content');
    ssImg = ssc.children('img');
    ssSrc = ssImg.attr('src').replace(window.location.protocol + "//" + window.location.host,'');
    genImage();
    jQuery(window).resize(function(){
        if(ssc.width()!=ssWidth){
            genImage();
        }
    });
});
function genImage(){
    ssImg.hide();
    ssWidth = ssc.width();
    ssImg.attr('src','/util/phpThumb/phpThumb.php?src='+ssSrc+'&w='+ssc.width());
    ssImg.show();
}
4

1 回答 1

1

我评论了代码,所以它应该是不言自明的:

jQuery(document).ready(function () {
  var contentWidth = $('#content').width();
  //find all images that do not have phpThumb.php in their src attr
  $('#content img:not([src*="phpThumb.php"])')
    //set their SRC attribute based on their current SRC attribute
    .attr('src', function (index, attr) { return '/util/phpThumb/phpThumb.php?src=' + attr.replace(window.location.protocol + "//" + window.location.host, '') + '&w=' + contentWidth });

  $(window).resize(function () {
    var contentWidth = $('#content').width();
    //find all thumbnails (those containing the string phpThumb.php iin their src attribute)
    var thumbs = $('#content img[src*="phpThumb.php"]')
                  //hide them (why?)
                  .hide()    
                  //update their SRC attribute, use regular expression to find the old width, and replace it with the new onee
                  .css('src', function (index, attr) { return attr.replace(/w=\d*$/, 'w=' + contentWidth); })
                  //show them again (why?)
                  .show()
  });
});
于 2013-07-30T06:09:01.917 回答