Creating a JQueryscript for GM - Trouble by rewriting the JS code

后端 未结 1 1943
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 21:58

after trying to solve the problem without and with help I\'m still stuck. My aim was writing a GM-script with JS. Someone told me to use jQuery because of its simplicity. Well,

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-24 22:23

    Ok, here's some semi-random pointers.

    1) Greasemonkey currently does not play nice with jQuery 1.4, so use jQuery 1.3.2. Incorporate it into your GM script by adding this line to the header:

    // @require     http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
    

    .
    .
    2) Stuff like this:

    document.getElementById("huhu").style.display = "none";
    document.getElementById("field1_show").style.display = "inline";
    document.getElementById("field1_hide").style.display = "none";
    

    .
    Becomes this with jQuery:

    $("#huhu").css          ('display', 'none');
    $("#field1_show").css   ('display', 'inline');
    $("#field1_hide").css   ('display', 'none');
    

    The jQuery version will work much better across different browsers, too.

    .
    .
    3) A very handy jQuery reference is at: http://www.jqapi.com/

    .
    .
    4) Here is a sample Greasemonkey script with your table-create, refactored the jQuery way. It works, as-is on the Google homepage. Adjust the header and TargetNode to match your target site. : (Warning: This sample script will create your table, but you can't bind the onClicks, etc., this way in a Greasemonkey script. See: GM pitfalls.)

    // ==UserScript==
    // @name           jQuery Test/Demo
    // @namespace      Google
    // @include        *.google.tld/
    // @require        http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
    // ==/UserScript==
    
    
    /* Optional:
    window.addEventListener ("load", Greasemonkey_main, false);
    */
    $(document).ready (Greasemonkey_main);
    
    
    function Greasemonkey_main ()
    {
        /*--- Get the first node inside the id="main" span (Google.com)
            If that's not there, then get the first node of the html body.
        */
        var TargetNode  = $("#main *:first");
        if (!TargetNode)
            TargetNode  = $("body *:first");
    
        $(TargetNode).after
        (
              ""
            + ""
            + ""
            + ""
            + "
    " + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
    " + "" + "Text
    " + "
    " + "" + "Text
    " + "
    " + "" + "Text
    " + "
    " + "" + "Text
    " + "
    " + "
    " + " " + "Text
    " + "
    " + "
    " ); }

    0 讨论(0)
提交回复
热议问题