-1
所以我有一個XML可以保存4張圖片,我的JS想要在XML內部拉取圖片並在點擊按鈕後顯示它們。但是當我運行我的程序時,按鈕顯示出來並且是可點擊的。但是當我點擊按鈕時,即使我在點擊功能中調用它,它也不會顯示,也不會顯示它裏面的圖片。有誰知道爲什麼?Javascript按鈕點擊功能不起作用
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");
}
什麼是$(document.getElementById(「button」))? – epascarello
您正在將一個單擊事件綁定到一個元素,然後它就存在。將處理程序綁定放入'$(document).ready'塊中。 – jbabey
你爲什麼要做'$(document.getElementById(「button」))'? –