javascript - 如何控制 document.write 写入的位置

标签 javascript

我想让我的 javascript 从数组中打印一个随机引号。我设法做到了这一点,但不知道如何控制它的写入位置。我想把它写在一个 div 中。帮忙?

代码:

quotes = [];
quotes[0] = "I have a new philosophy. I'm only going to dread one day at a time.";
quotes[1] = "Reality is the leading cause of stress for those in touch with it.";
quotes[2] = "Few things are harder to put up with than the annoyance of a good example.";
quotes[3] = "The pure and simple truth is rarely pure and never simple.";
quotes[4] = "There's no business like show business, but there are several businesses like accounting.";
quotes[5] = "Man invented language to satisfy his deep need to complain.";

//calculate a random index
index = Math.floor(Math.random() * quotes.length);

//display the quotation
document.write("<p>" +  quotes[index] + "</p>");

最佳答案

给 div 一个 id 说 divid 然后使用 document.getElementById()然后得到 div innerHTML设置其内容;

quotes = [];
quotes[0] = "I have a new philosophy. I'm only going to dread one day at a time.";
quotes[1] = "Reality is the leading cause of stress for those in touch with it.";
quotes[2] = "Few things are harder to put up with than the annoyance of a good example.";
quotes[3] = "The pure and simple truth is rarely pure and never simple.";
quotes[4] = "There's no business like show business, but there are several businesses like accounting.";
quotes[5] = "Man invented language to satisfy his deep need to complain.";

//calculate a random index
index = Math.floor(Math.random() * quotes.length);

//display the quotation
document.getElementById('divid').innerHTML = "<p>" +  quotes[index] + "</p>";

关于javascript - 如何控制 document.write 写入的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14369474/

相关文章:

javascript - 多个 setState 排队并导致一切都感觉很慢

javascript - 向表中添加新行/列

javascript - 使用 ui.router AngularJs 进行路由

javascript - 使用 Google map 绘制查询的热门结果

javascript - highchars-Angular 不渲染图表

javascript - Cloudinary cl_image_upload 与 cl_image_upload_tag

javascript - 生成一个 10 的倍数的随机数

javascript - jQuery 点击功能未更新

javascript - 防止在作为参数传递的函数中丢失 'this' 变量的上下文

javascript - slickgrid 条件格式和选择着色优先级