jquery - "Uncaught TypeError: Cannot set property ' left ' of undefined"使用内容脚本 Chrome 扩展中的 jQuery

标签 jquery google-chrome-extension

我尝试使用 jQuery 遍历要注入(inject)代码的页面的 DOM,但不断收到此错误。

我的 list 文件是:

{
  "name": "Jive enhancer",
  "version": "2.0.0",
  "description": "",
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "icons": {
    "48" : "sample-48.png",
    "128" : "sample-128.png"
  },
  "content_scripts": [
    {
      "matches": ["https://*/*"],//just for the question
      "js": [
            "jquery-1.7.2.js",
                "contentscript.js"
                ]
    }
  ]
}

这是我的 contentscript.js:

function test () {
    console.log ("injected");
    $("j-comm-activity-list").style.left="100px";   
}

test();

我的内容脚本被注入(inject)的页面有一个带有此 id 的 div:“j-comm-activity-list”,但由于某种原因我不断收到此错误。 从控制台执行相同的命令效果很好。我很绝望!

谢谢

最佳答案

使用 jQuery (Sizzle) 选择器,就像在 CSS 中一样,您可以使用 # 来表示 id。不带 # 的选择器 $("j-comm-activity-list") 正在搜索标签名为 j-comm-activity-list 的元素,而不是具有该 id 的元素。您想使用 jQuery ID Selector .

jQuery 对象也没有 style 属性。您可以使用数组表示法获取您选择的 DOMElement,如 $("#j-comm-activity-list")[0] (这是 $("#j-comm- Activity-list").get(0)。但最好使用内置 jQuery 函数,如 css :

$("#j-comm-activity-list").css('left', 100);

关于jquery - "Uncaught TypeError: Cannot set property ' left ' of undefined"使用内容脚本 Chrome 扩展中的 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11060754/

相关文章:

jquery - 我可以将 angular-selectize 与 require.js 一起使用吗?

google-chrome-extension - Chrome 打包的应用程序窗口在 Windows 8 上最大化为全屏

javascript - Google Chrome 扩展程序看不到点击次数?

jquery - 如何在 Chrome 扩展 contentscript 中使用 jQuery 而不发生冲突

php - jQuery:将变量传递给 php

php - WooCommerce update_checkout 不会更新送货方式

google-chrome - 使用 Lighthouse 发送 header

google-chrome - Google Chrome扩展程序可以修改页面内容吗?

jquery - Codrops 缩略图网格预览在顶部?

javascript - 在 angular.js 应用程序中维护页面刷新时的客户端页面状态