简体   繁体   中英

Why is javascript closing page tags?

I have a simple js that outputs html based on a vendors variables

if (icAnalytics == "1"){//Analytics
    $("#anal22").html("<a class='test1 test2 test33' href=/dashboard/site_sum.asp?id=application>Analytics</a>");
        };

if (icPermissions >= "1"){//Publishers
            $("#pub22").html("<a tabindex='0' href=/admin/default.asp class='ubermenu-target ubermenu-target-with-icon ubermenu-item-layout-default ubermenu-item-layout-icon_left'><i class='ubermenu-icon fa fa-lock'></i><span class='ubermenu-target-title ubermenu-target-text'>Pub</span></a>");
            }

if (icPermissions == "2"){//Admins
        $("#admin22").html("<a class=aTop2 href=/system/default.asp>Admin</a>");
        }

else {
 };

The problem is when I had the html to a "li" - so <li id="pub22"> it automatically closes the "li" even though I haven't added that code into it. I can't really change the layout of the page as I don't have access to it. Is there a way to keep the li from closing after inserting the html from javascript?

Note - This is a little bit more complex. The pub22 li is the first and then the anal22 and admin22 are nested and have different perms. Since they are nested I wanted to leave the li open. Maybe I am making this too hard.

As soon as you add any HTML to the DOM with JavaScript, the web browser is going to try to parse that HTML. If you create an <li> element without closing it, the browser is gonna be like "whoa, that's not valid HTML; I'll just fix that" and it'll automatically close the tag.

But all hope is not lost! Instead of adding code to the DOM as you write it, store it all in a string and only add the string to the DOM once you're done with it.

Here's an example:

var myHtml = "<li>"
myHtml += "blah blah this is some content";
myHtml += "</li>";
$("#someElement").html(myHtml); //we add the html to the DOM only now that we're done writing it

What you need to do something like:

$element = $('<li id="pub22">...</li>');
$element.append('<a id="anal22" href="...">...</a>');
$element.append('<a id="admin22" href="...">...</a>');
$element.appendTo('#someContainerElement');

Here you create your <li> , append a few <a> elements to it, and then finally attach the <li> to some existing element in the DOM. Creating elements in this way and attaching them to DOM when you are ready to make active is one of the key features of jQuery (in fact this is part of the base jQuery function).

jQuery's .html uses JavasScript's .innerHTML

.innerHTML inserts nodes into the DOM. A node, by definition, has to be valid markup. So the browser is correcting your bad markup on the fly.

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