【问题标题】:If URL Element Exists in IMG SRC如果 IMG SRC 中存在 URL 元素
【发布时间】:2013-07-30 03:33:56
【问题描述】:

如何编写 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();
}

【问题讨论】:

    标签: jquery image url src javascript


    【解决方案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()
      });
    });
    

    【讨论】:

    • 谢谢你,吉顿!不幸的是,我的代码肯定有不同的问题。修复并不像我想象的那么简单——不过,从什么时候开始?! :)
    • 我将完整粘贴我的代码,并修改我的问题。也许这样会更有意义。
    • Gidon - 您知道如何根据我对原始问题的更新使此代码正常工作吗?感谢您迄今为止的帮助!
    • 哇,吉顿,太棒了!有用!只有一个小问题。当窗口调整大小时,图像实际上并没有调整大小。如果我刷新页面,图像将调整大小。除了那件小事,你的编程技巧真是太棒了!您知道,这可能很好,因为大多数人不会在笔记本电脑和台式机以外的设备上调整窗口大小,这些设备通常具有足够好的互联网连接来处理较大/未调整大小的图像。非常感谢!!!
    • 现在我正在使用这段代码,我们可以更进一步,让脚本在其他选择器而不是#content 上运行,例如:.one、.two、.three ,.四等?我尝试通过用逗号分隔新选择器来做到这一点,但这不起作用。仅当只有 1 个选择器(例如“.three”)时,该脚本才会运行。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2015-08-17
    • 2012-01-12
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多