单击使用jquery获取div类ID

时间:2013-02-15 16:02:57

标签: javascript jquery html google-chrome-extension

如果听起来太简单,请跟我说。

我正在编写一个chrome扩展程序,一旦用户右键单击页面中的某个对象,就会出现上下文菜单,并且他可以选择获取所点击的div-class + ID的ID。

我已经为此工作了几天,并设法将额外的按钮添加到上下文菜单中。单击任何这些按钮后,将记录页面的源。可能花了我更少的时间来做这件事,但这是我第一次用javascript编写而且我一路上都被卡住了。

无论如何我不想要页面的整个html代码,而是单击的div-class。我在google搜索后发现,最好的方法是使用jquery的“html”函数而不是纯javascript。问题是它对我不起作用。

这是我的代码:

BackgroundPage(这里似乎一切正常)

    function genericOnClick(tab) 
    {
        console.log(tab.pageUrl);

        chrome.tabs.getSelected(null, function(tab) 
        {
            chrome.tabs.sendMessage(tab.id, {action: "getSource"}, function(source) {
            console.log(source);
            });
        });

    }


    // Create a parent item and two children.
    var parent1 = chrome.contextMenus.create({"title": "Rank Trigger", "contexts":["all"]});

    var child1 = chrome.contextMenus.create
    (

    {"title": "Rank 1", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
var child2 = chrome.contextMenus.create
(
    {"title": "Rank 2", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
var child3 = chrome.contextMenus.create
(
    {"title": "Rank 3", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);

ContentPage :(问题在这里)

chrome.extension.onMessage.addListener(function(request, sender, callback) 
{
    if (request.action == "getSource")
    {
     // callback(document.documentElement.outerHTML); //here i can get the page's whole source, I only want the clicked div class
     callback($('div class).html(); <--- something wrong here
    }

  });

清单文件:

{
  "name": "x",
  "description": "x",
  "version": "0.1",
  "permissions": ["contextMenus", "tabs"],
  "content_scripts": 
  [
    {
      "matches": ["http://*/*","https://*/*"],
      "js": ["jquery.js", "content.js"],
      "run_at": "document_end"
    }
  ],
  "background": 
  {
    "scripts": ["background.js"]
  },
  "manifest_version": 2
}

有什么想法吗?我再次知道我的问题看起来很简单,但我自学了这一切,并且出于某种原因,我发现网络编程比应用程序编程更难。

非常感谢。

编辑:为了澄清我想要的html源代码是: <div class="story reviewed-product-story" data-story-id="488481648"....</div>。 我想要这个div类,以便我可以解析它以获取data-story-id。如果有办法获得ID而不先获得div类,那么这也可以工作(甚至可能更好)

编辑:感谢Adeneo,我现在可以在页面的源代码中获取第一个div类的ID,但不能点击被点击的ID。向前迈进了一步,但不完全是我需要的东西。 也许我必须在使用$('。story')。data('story-id')之前获得clicked div的来源。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我猜它应该是:

chrome.extension.onMessage.addListener(function(request, sender, callback) {
    console.log('message listener');
    if (request.action == "getSource") {
        callback( $('.story').data('story-id') );
    }
});
相关问题