循环遍历数组并将结果输出到html

时间:2014-04-13 05:06:54

标签: javascript arrays loops

我有这个方法speak(),它有两个参数。它是原型的属性,因此多个对象将使用它。

我想抓住它返回的值,循环遍历它们,并将它们输出到我的html。我无法弄清楚的部分是,如何将每个段落标记与每个变量生成结果的每个输出对应? 这需要双循环吗?我输了。  var para = document.querySelectorAll(' p');

var speak = function(what, job) {
    var whoWhat = this.name + ' says, ' + what,
        whoJob = this.name + "'s job is: " + job;
    console.log(whoWhat);
    console.log(whoJob);
    return whoWhat, whoJob;
};

function Peep(name, job) {
    this.name = name;
    this.job = job;
}

Peep.prototype.speak = speak;

var randy = new Peep('Randy', 'lawyer');
randy.speak('"blahblah"', randy.job);

var mandy = new Peep('Mandy', 'mom');
mandy.speak('"woooooaahhhh"', mandy.job);

这里是jsfiddle

2 个答案:

答案 0 :(得分:1)

检查一下 - jsFiddle

继续将HTML添加到文本中。最后将它们添加到DOM中。

var speak = function(what, job) {
    var whoWhat = this.name + ' says, ' + what,
        whoJob = this.name + "'s job is: " + job;
    console.log(whoWhat);
    console.log(whoJob);
    return "<p>"+whoWhat+", "+whoJob+"</p>";
};

var txt = "";
var randy = new Peep('Randy', 'lawyer');
txt+=randy.speak('"blahblah"', randy.job);

var mandy = new Peep('Mandy', 'mom');
txt+=mandy.speak('"woooooaahhhh"', mandy.job);
document.getElementById('result').innerHTML = txt;

//in HTML add the result node
<body>
  <p id='result'>
  </p>
</body>

答案 1 :(得分:1)

使用JavaScript,您可以访问DOM(文档对象模型),并可以将新元素附加到现有元素。例如,您可以创建一个新的段落元素,并将此段落元素添加到ID为“result”的现有div中。这是一个例子:

 var appendText = function (text, parentId) {
     var para = document.createElement("p");
     var node = document.createTextNode(text);
     para.appendChild(node);
     var parentElement = document.getElementById(parentId);
     parentElement.appendChild(para);
 }

 var speak = function (what, job) {
     var whoWhat = this.name + ' says, ' + what,
         whoJob = this.name + "'s job is: " + job;
     return [whoWhat, whoJob];
 };

 function Peep(name, job) {
     this.name = name;
     this.job = job;
 }

 Peep.prototype.speak = speak;

 var randy = new Peep('Randy', 'lawyer');
 var randySays = randy.speak('"blahblah"', randy.job);
 appendText(randySays[0], "result");
 appendText(randySays[1], "result");

 var mandy = new Peep('Mandy', 'mom');
 var mandySays = mandy.speak('"woooooaahhhh"', mandy.job);
 appendText(mandySays[0], "result");
 appendText(mandySays[1], "result");

以下是具有所需html的jsfiddle:http://jsfiddle.net/stH7b/2/。您还可以在此处找到有关如何将段落附加到DOM的更多信息:http://www.w3schools.com/js/js_htmldom_nodes.asp