简体   繁体   中英

How to add multiple HTML code using $(“body”).append() in jQuery?

I am trying to make a bookmarklet using jQuery, but I am getting a syntax error while appending multiple HTML commands in the body using $("body").append(" "); Is there any other way to append multiple HTML commands using jQuery?

Actually, I was making this Bookmarklet in reference to a tutorial: https://www.smashingmagazine.com/2010/05/make-your-own-bookmarklets-with-jquery/

I am even sending the code for the bookmarklet:

bookmarklet.js

(function () {

    var v = "1.3.2";

    if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
        var done = false;
        var script = document.createElement("script");
        script.src = "http://ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js";
        script.onload = script.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                done = true;
                initMyBookmarklet();
            }
        };
        document.getElementsByTagName("head")[0].appendChild(script);
    } else {
        initMyBookmarklet();
    }

    function initMyBookmarklet() {
        (window.myBookmarklet = function () {
            function getSelText() {
                var s = '';
                if (window.getSelection) {
                    s = window.getSelection();
                } else if (document.getSelection) {
                    s = document.getSelection();
                } else if (document.selection) {
                    s = document.selection.createRange().text;
                }
                return s;
            }
            if ($("#wikiframe").length == 0) {
                var s = "";
                s = getSelText();
                if (s == "") {
                    var s = prompt("Forget something?");
                }
                if ((s != "") && (s != null)) {
                    $("body").append("<div id='wikiframe'>
                                      <div id='wikiframe_veil' style=''>
                                      <p>Loading...</p>
                                      </div>
                                      <iframe src='http://en.wikipedia.org/w/index.php?&search=" + s + "' onload=" $('#wikiframe iframe').slideDown(500); ">Enable iFrames.</iframe>
                                    <style type='text/css'>
                                                    #wikiframe_veil { display: none; position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(255,255,255,.25); cursor: pointer; z-index: 900; }
                                                    #wikiframe_veil p { color: black; font: normal normal bold 20px/20px Helvetica, sans-serif; position: absolute; top: 50%; left: 50%; width: 10em; margin: -10px auto 0 -5em; text-align: center; }
                                                    #wikiframe iframe { display: none; position: fixed; top: 10%; left: 10%; width: 80%; height: 80%; z-index: 999; border: 10px solid rgba(0,0,0,.5); margin: -5px 0 0 -5px; }
                                    </style>
                                    </div> "); //the append tag ends here, but the browser is showing syntax error on appending multiple HTML codes
                    $("#wikiframe_veil").fadeIn(750);
                }
            } else {
                $("#wikiframe_veil").fadeOut(750);
                $("#wikiframe iframe").slideUp(500);
                setTimeout("$('#wikiframe').remove()", 750);
            }
            $("#wikiframe_veil").click(function (event) {
                $("#wikiframe_veil").fadeOut(750);
                $("#wikiframe iframe").slideUp(500);
                setTimeout("$('#wikiframe').remove()", 750);
            });
        })();
    }

})();

So is there any way to get rid of this error. I hope my question is clear enough. Thanks in advance!

Unfortunately JavaScript breaks the parsing when you have a text string on multiple lines like that, you have to open and close the quotes on the same line. However there are few ways to cope with this:

You should collapse the .append() argument on a single line and return a single continuous HTML string like this:

$("body").append("<div id='wikiframe'><div id='wikiframe_veil' style=''><p>Loading...</p></div></div>");

or if you want to keep code indented for better legibility then you can concatenate the multiple lines appending a plus at the end of each line like this:

$("body").append("<div id='wikiframe'>" + 
                     "<div id='wikiframe_veil' style=''>" +
                          "<p>Loading...</p>" +
                     "</div>" +
                 "</div>");

My suggestion (and probably ideal way as it looks cleaner) would be to load an array with your lines of HTML, then join the array again with an empty space in this fashioned way:

var html = [
  '<div id="wikiframe">',
     '<div id="wikiframe_veil" style="">',
        '<p>Loading...</p>',
     '</div>',
  '</div>',
];

$("body").append(html.join(''));

Now, your code is clean, readable and the HTML injected on the page would single line and already compressed

https://jsfiddle.net/e2bt47c0/

Perhaps you could put the HTML in a single line (no cr break) or escape them with '\\' eg:

"<div id='wikiframe'><div id='wikiframe_veil' style=''><p>Loading...</p></div>"

or,

"<div id='wikiframe'>\
    <div id='wikiframe_veil' style=''>\
    <p>Loading...</p>\
    </div>\
</div>"

Another approach, using the Grave accent symbol ( ` ):

`<div id='wikiframe'>
    <div id='wikiframe_veil' style=''>
    <p>Loading...</p>
    </div>
</div>`

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