[英]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.