简体   繁体   中英

How to put HTML inside of a jquery or javascript function to to be appended later?

Sorry there might be an answer somewhere out there, but I was having trouble finding it as well as trying to do it myself. But I was wondering if I could get an example of putting HTML inside of a jQuery function as well as a javascript function so that I can use it later to append to DOMs.
HTML

<div class="container>
</div>

jQuery

$(function (nothing){
  '<h3>Nothing Here</h3>'
             });

$(".container").append(function(nothing));

RESULT

Nothing Here

I am an even bigger noob with javascript, but I'd like to achieve the same result. Can someone show me how? Also, is there a difference in using the javascript method VS the jQuery method? thanks!

Javascript answer: domElement.innerHTML is the API to add any html content inside the domElement. And the html content can be returned from the javascript function in string format.

<!DOCTYPE html>
<html>
<body>

<div id="container">
</div>

<script> function getHTMLContent() {
return "<h2>Nothing here</h2>";

}</script>

<script>
document.getElementById("container").innerHTML = getHTMLContent();
</script>

</body>
</html>

Jquery answer: Instead of .innerHTML we have .append in jquery. This also takes string as parameter. And there is no difference in the way we call the javascript function.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  function getHTMLContent() {
return "<h2>Nothing here</h2>";
}

$("#container").append(getHTMLContent());
});
</script>
</head>
<body>

<div id="container">
</div>
</body>
</html>

And regarding your doubt on function() and $function()..

$(function() { ... }); 

is just jQuery short-hand for

$(document).ready(function() { ... });

It gets called automatically once the page is ready.

But in javascript when you declare function() , this is not called by itself. You have to explicitly call it.

function nothing(){
  $(".container").append('nothing');
}

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