简体   繁体   中英

How do I add text to a paragraph tag via JQuery?

I'm trying to write my first chrome extension to test my acquired knowledge from codecademy (HTML/CSS, JQUERY and Javascript). First of all I'm trying to append text to a paragraph tag via the onclick of a button.

heres my code:

  <!doctype html>
<html>
    <head>
        <title>Facebook event graph</title>

        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
        <script src="popup.js"> </script>
    </head>
    <body>
        <form id="inputUrl">
                Enter a URL:  <input type="text" name="url" id="url">
                <button type="button" onclick="getFacebookData()"> Get Data </button>
        </form>
        <canvas id="graph" width="300" height="100">   
        </canvas> 
        <p id="text" width="300" height="100">1</p>
    </body>
</html>

and my popup.js:

$(document).ready(function(){

    //Variables
    function getFacebookData() {
        $('p').append('Test');
    };
});

it's probably something very basic that I'm doing wrong, but a push in the right direction would be really appreciated :)

  1. You are not allowed to use inline scripting like onclick="getFacebookData()"

    You have to remove the handler from html:

     <button type="button" id="my-button"> Get Data </button> 

    And you have to move the handler into popup.js:

     $(document).ready(function(){ $('#my-button').click(getFacebookData); }); 
  2. You are also, by default, not allowed to load jQuery from an external CDN - and certainly not http one, again for Content Security Policy reasons. And you shouldn't! Put jQuery in your extension's folder and load it locally.

  3. Matter of taste, but I would place getFacebookData() definition outside $(document).ready , so it's available in the global scope. Also, the semicolon after it is not needed.

Last, but not least: for future debugging , inspect the console of the corresponding page of your extension. For things like background/options page you should be able to access them from Developer Mode extensions list. For a popup, you should right-click the button of your extension and select "Inspect Popup".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM