首页 > 解决方案 > jQuery 代码不会在 chrome 扩展的内容脚本中运行

问题描述

我只是想知道是否有人对为什么此代码不会在我的 chrome 扩展的内容脚本中运行有任何意见。扩展程序设置正确,因为我在内容脚本中有可以正常工作的代码,由于某种原因,该代码根本无法工作。当我将它粘贴到代码需要运行的页面的控制台时,该代码就会运行。

代码:

function ucall(user) {
    window.open('test.com/userid=' + user, 'popup', 'width=600', 'height=600')
};
console.log("READY?")
var comments = document.getElementsByClassName('group-comments')[0]
console.log(comments)
$(comments).on('hover', '.wall-comment', function () {
    var user = $(this).find('a')[1].href;
    user = user.replace(/[^\d]/g, ''); console.log(user);
    console.log("do you hover bro?")
    $(this).css({ 'background-color': 'yellow' });
    $(this).click(function () {
        ucall(user)
    })
});

我为什么它可能不起作用的理论是我认为在变量“comments”中声明的 div 没有及时加载以执行代码。所以我试着做$(comments).ready(function(){//code here});那仍然没有用。我很困惑。此外,我的内容脚本中的所有代码都在一个

$(document).ready(function(){// all content script code in here})

标签: javascriptjquery

解决方案


在这里我添加了代码请检查这个..

function ucall(user) {
    window.open('test.com/userid=' + user, 'popup', 'width=600', 'height=600')
};
console.log("READY?")
// Here I have selected the first instance of the class using jQuery
var $comments = $('.group-comments').first();
console.log(comments)
//Used jQuery Instance directly.
$comments.on('hover', '.wall-comment', function () {
    var user = $(this).find('a')[1].href;
    user = user.replace(/[^\d]/g, ''); console.log(user);
    console.log("do you hover bro?")
    $(this).css({ 'background-color': 'yellow' });
    $(this).click(function () {
        ucall(user)
    })
});

推荐阅读