簡體   English   中英

使用jQuery更改img的src

[英]Changing src of img using jquery

我知道之前曾有人問過這個問題,但是我的代碼仍然無法正常工作,我也不知道為什么。 我正在嘗試創建一個Chrome擴展程序,以單擊更改類'profilePic img'的圖像

到目前為止,這是我的代碼:background.js:

chrome.browserAction.onClicked.addListener(function (tab) {
    if (tab.url.indexOf("https://www.facebook.com") != -1) {
        chrome.tabs.executeScript(tab.id, {
            "file": "contentscript.js"
        }, function () { 
            console.log("Script Executed"); 
        });
    }
});

contentscript.js:

alert("alert");
$(document).ready(function() {
$(document).find('.profilePic img').attr('src', 'second.jpeg')    
});

manifest.json

{
  "name": "stuff",
  "version": "0.0.1",
  "manifest_version": 2,

  // Recommended
  "description": "replaces fb profile pictures",
    "web_accessible_resources": [
    "second.jpeg"
  ],
 "background":{
            "scripts":["background.js"],
            "page": "background.html"
        },
         "permissions":["https://www.facebook.com/*"],
  "content_scripts": [
        {
            "matches":["http://www.facebook.com/*"],
            "js":["jquery-2.1.4.min.js","background.js","contentscript.js"],
            "all_frames": true,
            "run_at": "document_start"
        }
    ],
    "browser_action": {
  "default_icon": "icon.png",
  "default_title": "testing"
}
}

警報彈出就好了,但是什么都沒有改變...我的清單編輯中已經包含了jquery:我認為這是上傳jquery的問題,因為控制台日志錯誤是“未定義$”。 抱歉! 在這里完成初學者:(

這很可能發生,因為profilePic類用於img標簽。 Facebook個人資料圖片將profilePic與選擇器結合使用,這可能會讓您大跌眼鏡。 如果看起來像這樣,則當前形式的代碼可以工作,它將查找profilePic類,然后在其中找到所有img標簽,替換src屬性。

<div class="profilePic">
<img src="https://www.google.com/images/srpr/logo11w.png">
</div>

但是,由於圖像本身具有profilePic類,因此需要重構jQuery,使其看起來像這樣

$(".profilePic").attr("src","second.jpeg");

您也可以執行類似的操作,但我不確定完全如何將Facebook正常組合在一起,但這取自我的頁面。

$("#fbPageFinchProfilePic img").attr("src","second.jpeg");

您可以使用以下JSFiddle進行測試: http : //jsfiddle.net/u8zr55vz/1/

希望對您有所幫助! 請確保在此處閱讀jQuery .attr()以獲得更多信息。

暫無
暫無

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

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