简体   繁体   中英

Having Trouble Appending a Bunch of Html

I am having trouble appending a lot of html.

This is what I have:

$("#popup1").click(function(){
        $(".cd-popup-container").append("<p>Are you sure you want to decline this employement request?</p>");
        $(".cd-popup-container").append("<form id='accept_employe' action='/accept_employe' method='post' accept-charset='utf-8'>");
        $(".cd-popup-container").append("<ul class='cd-buttons no_margin'>");
        $(".cd-popup-container").append("<li><a class='submit'>Yes</a></li>");
        $(".cd-popup-container").append("<li><a class='popup-close'>No</a></li>");
        $(".cd-popup-container").append("</ul>");
        $(".cd-popup-container").append("</form>");
        $(".cd-popup-container").append("<a class=cd-popup-close popup-close img-replace>Close</a>");
    });

Obviously many appends will not work as it will only get the first one. However, when I put it all on the same line it doesn't work either.

How can I clearly append all this html into the .cd-popup-container?

Yea, you can (and should) definitely make it cleaner and easier to maintain. For example with array of strings and join by empty string:

$("#popup1").click(function() {
    var html = [
        "<p>Are you sure you want to decline this employement request?</p>",
        "<form id='accept_employe' action='/accept_employe' method='post' accept-charset='utf-8'>",
            "<ul class='cd-buttons no_margin'>",
                "<li><a class='submit'>Yes</a></li>",
                "<li><a class='popup-close'>No</a></li>",
            "</ul>",
        "</form>",
        "<a class=cd-popup-close popup-close img-replace>Close</a>"
    ].join('');
    $(".cd-popup-container").append(html);
});

And of course, it doesn't matter what approach you will take, the one I posted or more traditional with string concatenation, - the important part is that you don't perform many repetitive DOM appends, but rather combine them in bulks.

You can use a single append function by adding a + to the end of each line(except for the last line):

$("#popup1").click(function(){
    $(".cd-popup-container").append(
        "<p>Are you sure you want to decline this employement request?</p>" +
        "<form id='accept_employe' action='/accept_employe' method='post' accept-charset='utf-8'>" +
            "<ul class='cd-buttons no_margin'>" +
                "<li><a class='submit'>Yes</a></li>" +
                "<li><a class='popup-close'>No</a></li>" +
            "</ul>" +
        "</form>" +
        "<a class=cd-popup-close popup-close img-replace>Close</a>"
    );
});

JSFiddle

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