简体   繁体   English

如何在浏览器窗口中显示此javascript代码段的结果?

[英]How can I display the results of this javascript snippet in a browser window?

I'm fine with understanding what is happening in the console.log but I want to display the code in the browser window. 我很好理解console.log中发生的事情,但是我想在浏览器窗口中显示代码。 I think I should use document.write but I am unsure about this. 我认为我应该使用document.write,但是对此我不确定。

var friends = {
bill: {
    firstName: "Bill",
    lastName: "Gates",
},
steve: {
    firstName: "Steve",
    lastName: "Gates",
}
};

var list = function(friends){
for (var key in friends){
    console.log(key);
}
};

var search = function(name){
for (var key in friends){
     if (friends[key].firstName === name){
    console.log(friends[key]);
    return friends[key];
    }   
}
};

You could use the alert function 您可以使用alert功能

alert("Hello World")

or you could use 或者你可以使用

document.write("Hello World")

which outputs the string "Hello World" to the position of the js snippet in the html. 它将字符串“ Hello World”输出到html中js代码段的位置。 Alternatively, you could manipulate the DOM and set innerHTML on a div or span tag. 另外,您可以操纵DOM并在divspan标签上设置innerHTML If you add a tag with an id to your html like so, 如果您像这样向HTML添加带有ID的标签,

<span id="foo"></span>

you can set the html contents with 您可以使用

document.getElementById("foo").innerHTML = "Hello World"

Of course, if your problem is to serialize the result of your function, use JSON.Stringify 当然,如果您的问题是要序列化函数的结果,请使用JSON.Stringify

alert(JSON.stringify({"hello": "world", 3: "bar"}));

In order to show your hash you can use document.write, but you need to "stringify" your data like that : 为了显示您的哈希,您可以使用document.write,但是您需要像这样“字符串化”您的数据:

document.write(JSON.Stringify(friends));`

And if you would like something more beautiful : 如果您想要更美丽的东西:

document.write(JSON.stringify(friends, null, "<br/>"))

Documentation : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify 文档: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Another possibility is to use jQuery's .html() to modify an existing HTML element on your page. 另一种可能性是使用jQuery的.html()修改页面上的现有HTML元素。

var showFriends=function(){
var x = JSON.stringify(friends,null,'</br>');
$('#myDiv').html('<p>'+x+'</p>');
};

jsfiddle: http://jsfiddle.net/wLZff/ jsfiddle: http : //jsfiddle.net/wLZff/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM