JSP代码如下所示:
< img src='<%=imageURL%>' id='advt-image-top' border='0' alt=''" /><br/>imageURL的值是这样的,
http://1.2.3.4:5678/ads/avw.php?zoneid=1234567890&cb=INSERT_RANDOM_NUMBER_HERE
(从Ad-Server获取随机广告图像的URL示例)
现在,同一个JSP页面包含如下所示的javascript代码:
$(document).ready(function() {
var imgAd = new Image();
imgAd.src = '<%=imageURL%>';
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}
}
}上面的javascript代码检查-如果从ad-server返回的图像大小为1x1,则应将其替换为default-image。
问题是,上面的整个代码片段执行了两次"imageURL“,以便从ad-server获取一个图像:一次是检查从ad-server返回的图像的大小是否为1x1,另一次是在标签执行期间。
我如何优化上面的代码,使"imageURL“只执行一次?
如何将javascript的Image()对象(在通过1x1验证后)赋给JSP的'advt-image-top‘元素?提前谢谢。
发布于 2016-05-24 19:02:25
您只需要对javascript代码稍作调整,而不需要创建Image
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
}但是,图像可能会在文档就绪之前加载,并丢失onload事件,因此您可能希望在标记中加载默认url:
< img src='img/default_top.jpg' id='advt-image-top' border='0' alt=''" /><br/>...and通过代码应用远程url:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
}javascript EDIT:可能最好的方法是将img标记从jsp中完全删除,并使用编写所有内容。假设图像包含在id为“container”的元素中:
$(document).ready(function() {
var imgAd = new Image();
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
imgAd.id='adv-image-top';
imgAd.border=0;
document.getElementById('container').appendChild(imgAd);
}发布于 2016-05-24 21:32:55
@dipanda,感谢您的评论。帮我解决了我的问题。
var $imgObj = $("<img/>",{src:"<%=imageURL%>"});
$imgObj.load(function(){
var imgJS = $imgObj[0];
if(imgJS.height == 1 && imgJS.width == 1){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}else{
if($("#advt-image-top")!=null && $("#advt-image-top")!=undefined){
$("container").append($imgObj);
}
}
};https://stackoverflow.com/questions/37410883
复制相似问题