簡體   English   中英

jQuery html($(“ <img> ”).attr(“ src”,this.href)); 在Safari中無法使用

[英]jquery html($(“<img>”).attr(“src”, this.href)); not working in Safari

我正在為圖片庫使用簡單的jquery函數。 單擊縮略圖后有一個div,然后單擊縮略圖后將大圖像加載到其中的目標div。

它在所有瀏覽器中都能正常工作,但Safari除外,在Safari中,加載圖片的絕對URL而不是在div中加載。

這是jQuery代碼:

$("#thumbnails a").click(function() {
    $("#work").html($("<img>").attr("src", this.href));

    return false;
});

有什么想法嗎? 謝謝

this.href不安全!

使用$(this).attr('href') ,它將起作用。

在這里查看我的問題: 檢索HTML屬性值“ DOM 0方式”

它解釋說,有幾個有問題的HTML屬性(其中的href ),因此應使用jQuery的attr()來檢索其值。

引用該頁面上的答案:

例如,元素的href屬性始終報告完全限定的URL,而getAttribute(“ href”)將逐字返回HTML href屬性中指定的字符串。 當然,除了IE中。 jQuery的attr()確實試圖規范這種不一致。


更新

我想到了。 您沒有確保在DOM准備好后即可運行jQuery代碼。 始終將所有jQuery代碼放在ready處理程序中:

$(function() {

    // place all jQuery code here

});

更新2

試試這個代碼:

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

我應該早點看過。 html()函數的參數必須為字符串。


更新3

可能是Safari(至少)沒有執行頁面上完全通過jQuery的load()方法加載的JavaScript代碼。

但是,我認為我想出了應對方法!

在1776.php頁面上,將SCRIPT元素從HEAD移到文檔的BODY。

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

我對this.href感到困惑,因為當您在屬性$("#work")

嘗試這個:

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

僅在Safari Mobile中通過javascript附加圖像時,請使用css屬性background:url(...)代替<img>標記。 它不能與<img>標簽一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM