简体   繁体   中英

Using JavaScript how do I insert html code into my page?

Ok so I am using xhtml not html. I am getting data using a hidden xhtml component sending it to JavaScript. The data is a JSON array. I want to manipulate the data and format it adding xhtml tags and send back to the xhtml page and display it. How do I add the code to the < ul id="ticker01"> element?

Do I do something like:

var ticker01 = document.getElementById("ticker01");
ticker01.innerhtml = "<li><span>[15:38:00]</span><a href="#">Red fish</a></li><li><span>[15:39:00]</span><a href="#">Blue fish</a></li>"

Or like so with jQuery:

$( "<li><span>[15:38:00]</span><a href="#">Red fish</a></li><li><span>[15:39:00]</span><a href="#">Blue fish</a></li>" ).appendTo( "ticker01" );

xhtml page:

<h:body>
<h:inputText id="chatMessagesHidden" value="#{chatRoom.msgsAsJson}" style="display: none" />
        <ul id="ticker01">
                <li><span>[15:38:00]</span><a href="#">Red fish</a></li>
                <li><span>[15:39:00]</span><a href="#">Blue fish</a></li>
                <li><span>[15:39:30]</span><a href="#">Old fish</a></li>
                <li><span>[15:39:30]</span><a href="#">New fish</a></li>                    
        </ul>
</h:body>

JavaScript:

var chatMessages;
var chatMsg;

$(document).ready(function() {
    chatMessages = $('chatMessagesHidden');

    for (var i=0; i < chatMessages.length; i++) {
        chatMsg = chatMessages[i];
    // Manipulate the data to send back to xhtml page
    }                
});

Will either of these work or do I have to go up a tag level and insert the whole ul tag in the body??

Your code should work but you need to add # to target element by id :

chatMessages = $('.chatMessagesHidden');

Also, instead of for loop, you can use $.each()

$.each($('.chatMessagesHidden'), function(i) {
    chatMsg = chatMessages[i];
    // Manipulate the data to send back to xhtml page
});

I forgot to mention that id is unique, you need to use class instead:

<h:inputText class="chatMessagesHidden" value="#{chatRoom.msgsAsJson}" style="display: none" />

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