如何在没有正文的情况下打印函数的返回字符串?

时间:2016-09-08 10:20:50

标签: javascript html

我有一个包含4个段落的html文档。

我想将所有段落的innerHTML连接起来并将其放在带有“demo”id的段落中。问题是它还打印了函数的签名......

如何只打印函数返回的字符串?

<!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>

<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>

<p id="demo"></p>

<script >
    var paragraphs = document.getElementsByTagName("p");


    function getText() {
        var text=null;
        for (var i = 0; i < paragraphs.length; i++) {
            getText = getText + paragraphs[i].innerHTML;
        }
        return getText;
    }

    document.getElementById("demo").innerHTML=getText();

</script>

</body>
</html>

我得到了这个结果:

  

Hello World!

     

DOM非常有用。

     

此示例演示了getElementsByTagName方法

     

function getText(){var text = null; for(var i = 0; i&lt;   paragraphs.length; i ++){getText = getText + paragraph [i] .innerHTML;   } return getText; Hello World!DOM非常有用。这个例子   演示了getElementsByTagName方法

3 个答案:

答案 0 :(得分:3)

这是因为您正在返回该功能,而不是文本。

// Main function declaration
function getText() {

    // Setting the initial string (text) and all paragraphs (<p>)
    var text = "";
    var paragraphs = document.getElementsByTagName('p')

    // Loop over all paragraphs
    for (var i = 0; i < paragraphs.length; i++) {
        // use the .concat() function to combine the strings (with a space behind it)
        text = text.concat(paragraphs[i].innerHTML + " ");
    }

    // Return the string in variable text as a result of the function.
    return text;
}

// Enter the string in the demo p.
document.getElementById("demo").innerHTML = getText();

Here's a codepen (working) example.

答案 1 :(得分:2)

用以下功能替换您的功能:

function getText() {
        var text="";
        for (var i = 0; i < paragraphs.length; i++) {
            text= text+ paragraphs[i].innerHTML;
        }
        return text;
    }

在您的情况下,您返回getText这是您的函数名称,这也是该方法也被追加的原因

答案 2 :(得分:0)

您必须返回变量'text'而不是getText();

<!DOCTYPE html>
<html>
<body>

<p>Hello World!</p>

<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>

<p id="demo"></p>

<script>
    var paragraphs = document.getElementsByTagName("P");

    var text = "";

    function getText() { 
        var i; 
        for (i = 0; i < paragraphs.length; i++) {
           text += paragraphs[i].innerHTML;
        }
        return text;
    }

    document.getElementById("demo").innerHTML = getText();

</script>

</body>
</html>