开发者

jquery html($("<img>").attr("src", this.href)); not working in Safari

I'm using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

$("#thumbnails a"开发者_运维知识库).click(function() {
    $("#work").html($("<img>").attr("src", this.href));

    return false;
});

Any thoughts? Thanks


this.href is not safe!

Use $(this).attr('href') and it will work.

Check out my question here: Retrieving HTML attribute values "the DOM 0 way"

It explains that there are several HTML attributes (href among them) that are problematical, so one should use jQuery's attr() to retrieve their values.

Quote from an answer on that page:

For example, the href property of an element always reports a fully qualified URL while getAttribute("href") will return the string specified in the HTML href attribute verbatim. Except, of course, in IE. jQuery's attr() does attempt to normalize this kind of inconsistency.


UPDATE

I figured it out. You didn't ensure that the jQuery code runs after the DOM is ready. Always place all your jQuery code inside the ready handler:

$(function() {

    // place all jQuery code here

});

UPDATE 2

Try this code:

$('#thumbnails a').click(function() {
    $('#work').empty().html( '<img src="' + $(this).attr('href') + '">' );
    return false;       
});

I should have seen this earlier. The argument of the html() function has to be a string.


UPDATE 3

It could be that Safari (at least) does not execute JavaScript code that is on a page which is loaded entirely via jQuery's load() method.

However, I think that I figured out how to deal with it!

On the 1776.php page, move the SCRIPT element from the HEAD to the BODY of the document.

<body>
    <script> ... the code ... </script>
    <div> ... </div>
</body>


$("#thumbnails a").click(function() {
      $('#work').empty().append($('<img>', {
           src:   this.href
      }));
      return false;
});


I its getting confused off the this.href because while your in the attribute $("#work").

try this:

$("#thumbnails a").click(function() {
    var urlHref = $(this).attr('href');
    $("#work").html($("<img>").attr("src", urlHref));
    return false;
});


Use css property background:url(...) instead of <img> tag when appending images through javascript in Safari Mobile only. It won't work with <img> tags.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜