質問

I'm trying to make an chrome extention with the last.fm api, and I've succesfully placed down the folliwing div in the page I want it to be shown.

<div id="showLastFMInfo" Title="More info about song" class="LastFMButtonDown">&raquo;</div>

but when I click on it, nothing happens, this is the JS used:

$(document).ready(function () {
    // this get executed
    $('#meta-frame').append('<div id="showLastFMInfo" Title="More info about song" class="LastFMButtonDown">&raquo;</div>');

    // this won't work if I click on my button
    $("#showLastFMInfo").click(function(){
        console.log("Click");
    });
});

so you can see the first lines get executed but the .click() doesn't react.

this is my manifest.json:

{
   "content_scripts": [ {
      "js": [ "jquery.js", "lastfm.api.cache.js","lastfm.api.md5.js", "lastfm.api.js","lastFMLink.js", "script.js"],
      "css": [ "LastFMLink.css" ],
      "run_at": "document_end"
   } ],

   "name": "Plug.Dj VS last.Fm",
   "description": "Implement information about the artist",
   "icons": { "16": "cookie.png", "48": "cookie.png", "128": "cookie.png" },
   "version": "0.0.1",
   "web_accessible_resources": [ "lastFMLink.js" ],
   "manifest_version": 2
}

Does anyone has a idea what I'm doing wrong?

役に立ちましたか?

解決

You're appending it, so it's dynamic, and you need a delegated event handler:

$('#meta-frame').on('click', '#showLastFMInfo', function(){
    console.log("Click");
});

on the other hand, attaching the event handler after the element is appended should work as well?

他のヒント

for dinamically generated contents use on of these

    $("a.offsite").live("click", function(){ alert("Goodbye!"); });                // jQuery 1.3+
    $(document).delegate("a.offsite", "click", function(){ alert("Goodbye!"); });  // jQuery 1.4.3+
    $(document).on("click", "a.offsite", function(){ alert("Goodbye!"); });        // jQuery 1.7+

live and delegate are deprecated, so using .on() is recommended.

Use document or the closest static element

$(document).on('click','#showLastFMInfo',function(){

});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top