将返回值放在 HTML 中

Place Return Value in HTML

本文关键字:HTML 返回值      更新时间:2023-09-26

我有一个.js文件,其中包含一个返回HTML的函数。 如何从我的.html调用此函数并将其返回放置在进行调用的位置?

我的.html

<body>
    //should make the HTML tag for a <h1>h1</h1> or <h2>h2</h2>
    <script>
        my.js->myFunction();  //what goes here?
    </script>
</body>

我的.js

function myFunction(){
    if(true){
        return "<h1>h1</h1>";
    }
    else{
        return "<h2>h2</h2>";
    }
}

我正在使用jQuery。

你正在从PHP的思维方式思考。Javascript直接对DOM(文档对象模型(进行更改,不需要与HTML内联插入。举个例子:

<p> Hello <php echo "World"; ?> </p>

这就是PHP的方式。相比之下,这是Javascript的方法:

<p> Hello <span id="output"></span> </p>
<script>
   document.getElementById("output").innerHTML="World";
</script>

请注意此处document的使用。这就是DOM中的"D"。我们正在寻找一个嵌套在 document 中的元素,ID 为 "output",并将其 HTML 更改为 "World"。

如果你没有使用任何框架(jQuery,AngularJS等(,你可以

<p id="p1"></p>
<script>
function myFunction(){
    var text = "";
    if(true){
         text = "True";
    }
    else{
         text = "False";
    }
    $("#p1").html(text);
}
</script>