2014-09-09 2 views
0

제목과 텍스트로 구성된 여러 기사로 JSON 파일에서 내용을 가져 오는 뉴스 레터를 설정하려고합니다. JavaScript를 사용하여 HTML 페이지에 모든 제목이있는 목록을 표시하고 싶습니다. 사용자가 제목 중 하나를 클릭하면 해당 텍스트가 표시되어야합니다 (이상적으로 다른 제목을 클릭하면 이전 텍스트를 숨기고 새 텍스트 만 표시해야 함). 다른 반복에서).JavaScript로 두 번째 JSON 요소를 표시하는 방법은 무엇입니까?

스크립트는 제목을 나열하지만, ​​지금까지 HTML 링크로 만들었을 뿐이므로 innerHTML을 사용하여 div에 텍스트를 표시하려고했던 존재하지 않는 페이지로 사용자를 보냈습니다. . JSON 파일에서 텍스트 요소를 가져와 한 번에 하나씩 표시하는 방법을 누군가가 나에게 말할 수 있다면 기뻤습니다. JavaScript에 익숙하지 않고 jQuery에 대해 알지 못합니다.

내 JSON 데이터 :

var article = [ 
    { 
     "title": "This is title no. 1", 
     "text": "Here is the text of the first article" 
    }, 
    { 
     "title": "This is title no. 2", 
     "text": "Here is the text of the second article" 
    }, 
    { 
     "title": "This is title no. 3", 
     "text": "Here is the text of the third article" 

    } 
] 

내 HTML :

<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript" src="newsletter.json"></script> 
    <script type="text/javascript"> 
     function getData() { 
      for(i = 0; i < article.length; i++) { 
       document.getElementById("showData").innerHTML += "<li>" + article[i].title.link(article[i].text) + "</li>"; 
      } 
     } 
    </script> 
</head> 
<body onload="getData()"> 
    <div id="showData"></div> 
</body> 
</html> 
+2

귀하의 질문에 ** JSON과는 ** 아무 상관이 있습니다. 당신이 게시 한 것은 일반적인 * JavaScript 배열입니다. JSON으로 데이터를 가져온 경우에도 배열을 처리하는 데 문제가있는 것처럼 보이지 않으므로 관련이 없습니다. JSON은 언어에 구애받지 않고 텍스트 기반의 데이터 교환 형식입니다. 당신이 가지고있는,'var article = [...];'은 JavaScript입니다. –

+0

좋아, JSON 질문처럼 보이지만 데이터를 자바 스크립트 배열로 표시했습니다. 대신에 'newsletter.json'에서 데이터를 가져와야하고 그 배열을 사용하여 어떻게 작동하는지 보여줄 수 있습니까? – Popnoodles

+0

@Popnoodles : OP에서 제목을 표시 할 수 있다고 언급했기 때문에 '기사'는 실제로 다른 스크립트에 포함되어 있고 배열을 포함하고 있다고 생각합니다. –

답변

0

이 jQuery를 함께 할 매우 쉽습니다.

는 작업 바이올린 여기를 참조하십시오 : http://jsfiddle.net/manishie/pk7264u6/

HTML :

<body> 
    <div id="showData"></div> 
</body> 

자바 스크립트 :

function getData() { 
    var html = ''; 

    for(i = 0; i < article.length; i++) { 
     html += "<li data-text='" + "'>" + article[i].title.link(article[i].text) + "</li>"; 
    } 
    $('#showData').html('<ul>' + html + '</ul>'); 

    // Use jQuery 'on' to run code when any Anchor tag inside the #showData div is clicked. 
    $('#showData').on('click', 'a', function(e) { 

     // remove any previously displayed text (in divs with the .text class) 
     $('#showData .text').remove();  

     // after the current element (the anchor tag that was clicked) add a new div with the class .text. Inside that div, display the href attribute of the anchor tag that was clicked. 
     $(this).after('<div class="text">' + $(this).attr('href') + '</div>'); 

     // disable normal anchor handling so you don't get taken to a non-existent page. 
     e.preventDefault();  

    }); 

} 

// Use jQuery $(document).ready to make sure the DOM is loaded before you run anything (http://learn.jquery.com/about-jquery/how-jquery-works/) instead of the onLoad in body. 
$(document).ready(function() { 
    getData(); 
}); 
+0

고마워요. 나는 자바 스크립트 솔루션을 원했지만, 나에게 익숙해졌지만 더 복잡 할 수도 있다고 생각한다. 여하튼, 이것은 jQuery의 강력한 케이스를 만드는 것처럼 보입니다. 그래서 나는 그것을 진행하려고 노력할 것입니다. – Cunctator03

관련 문제