Safari not cool with HTML5 void elements; JavaScript is
I'm using JavaScript to generate an image object, and then using jQuery to alter its attributes, including a .load function. After a frustrating attempt to find Safari (ver 5.0.5)'s error console (most frustrating when, in the end, it was not hard to find), we discovered that Safari terminated its JavaScript when encountering unclosed img tags, which of course is deprecated in HTML5. I would simply hardwire the img tag in the function if that didn't make adding the load function rather nightmarish, if not impossible. Any ideas?
function loadImageTitle(imgsrc, element, width, height, title) {
var img = new Image();
$(img)
.load(function () {
$(this).hide();
$(element).replaceWith(this);
})
.css({ 'max-width': width, 'max-height': height })
.attr("title", title)
.attr("alt", title)
.attr("src", imgsrc);
}
I was actually kind of unclear about the most basic part of this. The problem is that JavaScript makes the img without a trailing slash (in Safari 5.0.5, in FF 4.0.1, in IE8, and in Chrome 13 -- so everywhere, near as I c开发者_运维知识库an tell), as, in HTML5, it is optional. Safari disagrees and terminates the script.
It's not clear what your code is trying to achieve. It looks like you're trying to replace an existing element with an image. You could do something like this:
var img = $("<img/>")
.load(function() { $(element).replaceWith(this); })
.attr({
title: title,
alt: title,
src: imgsrc
})
.css({
"max-width": width,
"max-height": height
})
I was going to use .hide() to hide the image, but it should be fine as is. Because the image hasn't been added to the document, it won't be visible anyway.
精彩评论