函数返回的打印值,以javascript格式显示

时间:2013-03-23 18:15:10

标签: javascript function

我编写了以下JavaScript函数:

<script type="text/javascript">
function showVariable(val){         
    if(typeof(val)!=null && typeof(val)!=false &&typeof(val)!=NaN && typeof(val)!=undefined)
        return typeof(val);
    else 
        return val;
}
function print(){
    var val = {1, 2, 3};
    var res = showVariable(val);
    alert(res);
}
</script>

目前,我可以使用alert查看结果,但我想知道是否有另一种方法可以在我的html文档中打印showVariable的结果。

6 个答案:

答案 0 :(得分:3)

只需使用

function print(){
    var val = {1, 2, 3};
    var res = showVariable(val);
    document.getElementById("myDiv").innerHTML = res;

   //if the target is an input :
   document.getElementById("myDiv").val = res;
}

答案 1 :(得分:2)

其他人已指出如何将文本添加到现有HTML元素。其他几个选项如下所述。

错误日志

对于调试,alert()的替代方法不太干扰,就是将文本添加到错误日志中。例如,在带有Firebug扩展的Firefox中:

if (console.log) console.log(res);

<强>文件撰写

可能不适用于此特定问题的另一个选项,但有时是有用的,是使用document.write。但是,在页面加载后请小心不要使用它,否则它将覆盖页面。

例如,以下内容:

<p>one</p>
<script type="text/javascript">document.write('<p>two</p>');</script>
<p>three</p>
<script type="text/javascript">document.write('<p>four</p>');</script>

将在浏览器中显示,就像静态HTML源代码一样:

<p>one</p>
<p>two</p>
<p>three</p>
<p>four</p>

<强> typeof运算

在旁注中,typeof运算符返回以下字符串值之一:

    'undefined'
    'null'          // For browsers that support ECMAScript 6+
    'boolean'
    'number'
    'string'
    'function'
    'object'

初始if语句可以重构如下:

Instead of this               Use this                     Or this
-------------------           -----------------            ------------
typeof(val) != null           val !== null
typeof(val) != false          val !== false
typeof(val) != NaN            typeof val == 'number'       !isNaN(val)
typeof(val) != undefined      typeof val != 'undefined'

不确定您是否需要所有这些测试。这取决于你想要做什么。

答案 2 :(得分:0)

如果是元素,可以将其设置为.innerHTML属性。像这样:

<div id="output"></div>

document.getElementById('output').innerHTML = val;

答案 3 :(得分:0)

您可以输出到元素:

HTML:

<div id="log"></div>

JavaScript的:

function print(value) {
    document.getElementById('log').innerHTML += value;
}

答案 4 :(得分:0)

您可以尝试document.write();

function print(){
        var val = {1, 2, 3};
        var res = showVariable(val);
        document.write(res);
    }

答案 5 :(得分:0)

大多数答案都是正确的。但对于初学者来说,这可能会令人困惑。 让我把它们分成几步:

问题:假设您要从文本框中收集值并将其打印到HTML正文中。

  • 第1步:声明任何带有ID&#39;结果的内容&#39; (或任何东西)
  • 第2步: 从文本框收集到变量。
  • 第3步:使用打印 的innerHTML

&#13;
&#13;
<html>
<body>

Hi everyone

<p id="result"></p>
<textarea cols="40" id="SearchText" rows="1"></textarea>

</div>
<button onclick="myFunction()" type="button">Submit!</button>
</div>
<script>
function myFunction() {
    var result = document.getElementById("SearchText").value;
	document.getElementById("result").innerHTML = 'hello' + result;
}
</script>

</div>

</body>
<html>
&#13;
&#13;
&#13;

相关问题