2013-11-20 3 views
-1

4 개의 사진을 보유하고있는 XML이 있고 JS는 버튼을 클릭하면 XML 내부의 이미지를 가져 와서 표시합니다. 그러나 프로그램을 실행하면 단추가 나타나고 클릭 할 수 있습니다. 그러나 버튼을 클릭하면 클릭 기능에서 호출해도 내 사진이 나타나지 않으며 사진도 표시되지 않습니다. 아무도 이유를 아나요?자바 스크립트 버튼 클릭 기능이 작동하지 않습니다.

var xml; 
var raceName; 
var raceSrc; 
$(document).ready(function() { 
    var xmlDoc = $.ajax({ 
     type: "GET", 
     url: "Lab8XML.xml", 
     dataType: "xml", 
     data: null 
    }); 
    $(document.getElementById("button")).click(function(){ 
     xml = $(xmlDoc.responseXML); 
     getRandomRace(); 
     $("<img src='" + raceSrc + "' alt='" + raceName + "' />").appendTo("#raceArea"); 
     $("#raceArea > h2").text(raceName); 
     setInterval(displayNewRace, 5000); 
    }); 
}); 

function displayNewRace() { 
    $("#raceArea").fadeOut("slow"); 
    setTimeout(changeRace, 500); 
    $("#raceArea").fadeIn("slow"); 
} 

function changeRace() { 
    getRandomRace(); 
    $("img").attr("src", raceSrc); 
    $("img").attr("alt", raceName); 
    $("#raceArea > h2").text(raceName); 
} 

//Math.random returns a number between 0 and .9999 
//Math.floor chops off the decimal place to make an int 
function randomInt(minInt, maxInt) { 
    return Math.floor(minInt + Math.random() * (maxInt - minInt +1)); 
} 

function getRandomRace() { 
    //call randomInt(minInt = 0, maxInt = array length - 1) 
    var $rand = randomInt(0, xml.find("race").length - 1); 
    //Pick out a random pokemon 
    var $randomRace = $(xml.find("race")[$rand]); 
    //Set the name and source to access them later 
    raceName = $randomRace.children("name").text(); 
    raceSrc = $randomRace.children("img").attr("src"); 
} 
+2

'$ (document.getElementById ("button")) 란 무엇입니까? – epascarello

+0

클릭 이벤트가 있기 전에 요소에 바인딩하고 있습니다. 핸들러 바인딩을'$ (document) .ready' 블록에 넣으십시오. – jbabey

+0

왜'$ (document.getElementById ("button"))'를하고 계십니까? –

답변

0

나는 어떤 코드를 잘못 것은 당신이 전화하고있는 기능 (getRandomRace)이 그 변수에 액세스 할 수 있도록 지역 변수 xml 대신에 전역 변수를 정의하고 있다는 생각합니다.

대신에 당신의 클릭 기능 내부 var xml = ...window.xml = ...를 수행하거나 액세스 할 수 있도록 더 나은, XML에게 getRandomRace 함수의 매개 변수를 확인하십시오.
행운을 빌어 요!

관련 문제