2014-04-13 3 views
0

두 가지 인수를 취하는 speak() 메서드가 있습니다. 프로토 타입의 속성이므로 여러 객체가이 객체를 사용합니다.배열을 통해 반복하여 결과를 html로 출력

반환하는 값을 가져 와서 반복하고 내 html로 출력하고 싶습니다. 내가 알 수없는 부분은 각 변수의 각 결과에서 각각의 출력과 일치하도록 각 개별 단락 태그를 어떻게 목표로합니까? 이중 루프가 필요합니까? 나는 길을 잃었다. var para = document.querySelectorAll ('p'); 텍스트에 HTML을 추가 jsFiddle

보관할 것 -

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

답변

1

확인이 하나입니다. 마지막으로 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

JavaScript를 사용하면 DOM (Document Object Model)에 액세스 할 수 있으며 기존 요소에 새 요소를 추가 할 수 있습니다. 예를 들어 새 단락 요소를 만들고이 단락 요소를 id가 "div"인 기존 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

관련 문제