抱歉,那里可能有答案,但我在找到它以及尝试自己做时遇到了困难。但我想知道是否可以获得一个将 HTML 放入 jQuery 函数以及 javascript 函数中的示例,以便我稍后可以使用它来附加到 DOM。
HTML
<div class="container>
</div>
jQuery
$(function (nothing){
'<h3>Nothing Here</h3>'
});
$(".container").append(function(nothing));
结果
Nothing Here
我是一个 javascript 菜鸟,但我想达到相同的结果。有人可以告诉我怎么做吗?另外,使用 javascript 方法与 jQuery 方法有区别吗?谢谢!
最佳答案
Javascript 答案:
domElement.innerHTML
是用于在 domElement 内添加任何 html 内容的 API。
并且 html 内容可以从 javascript 函数以字符串格式返回。
<!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 答案:jquery 中没有 .innerHTML
,而是 .append
。这也将字符串作为参数。而且我们调用javascript函数的方式没有什么区别。
<!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>
关于您对 function() 和 $function() 的疑问..
$(function() { ... });
只是 jQuery 的简写
$(document).ready(function() { ... });
页面准备好后,它会自动调用。
但是在 javascript 中,当您声明 function()
时,它本身不会被调用。您必须显式调用它。
关于javascript - 如何将 HTML 放入 jquery 或 javascript 函数中以便稍后添加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60882418/