如何编写jQuery代码来表明,"如果' page.php'存在于img src中,然后不运行'示例功能'在那个img。如果' page.php'在img src中不存在,然后运行'示例函数'在那张图片上。"?
该页面将包含多个图片,而且并非所有图片都会显示' page.php'在图像src。
这是我迄今为止尝试过的代码没有成功:
<script type="text/javascript">
if (jQuery('img').attr('src').indexOf('page.php') >= 0) {
example();
}
</script>
编辑#1:
以下是我的整个脚本。基本上,我不想在已经拥有&#39; phpThumb.php&#39;的图像上运行此脚本。在他们的src网址中。
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();
}
答案 0 :(得分: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()
});
});