所以我有这段代码可以点击一个 div
$("#instructbox").click(function() {
alert("test");
});
但是,它只有在我将它放在另一个函数中时才有效,例如我的 document.ready 函数,或者奇怪的是,任何其他 JS 函数。我一直对 jQuery 感到疑惑,现在我想要一个答案;p 另外,如果我将它放在 HTML 底部的标签中,它也可以正常工作。
在全:
var words = new Array();
var sylls = new Array();
var csv_file = new Array(); // for word arrays
$(document).ready(function() {
$.ajax({
type: "GET",
url: "terms.csv",
dataType: "text",
success: function(data) {processData(data);}
});
// generate a haiku!
$("#instructbox").click(function() {
alert(writeLine(5));
});
});
function processData(allText) {
csv_file = allText.split('\n');
// csv file is now in an array, split into seperate word array and syllable array
for (var i = 0; i < csv_file.length; i++) {
var both = csv_file[i].split(','); // split at the comma
words[i] = both[0]; // populate word array
sylls[i] = both[1]; // populate syllable array
//put_word(words[i], sylls[i]);
//alert(words[i]);
}
put_word();
};
// put the words into the marquee
function put_word() {
//console.log(words);
// place the words into 'words' div
var divID = document.getElementById("wordlist"); // grab 'words' div
//divID.innerHTML = words;
for (var i = 0; i < words.length; i++) {
divID.innerHTML += words[i] + " ";
//divID.innerHTML += "<span>" + words[i] + "</span>" + "<sup>" + sylls[i] + "</sup> ";
};
}
function writeLine(syls) {
var haikuLine = "";
var sylLeft = syls;
while ( sylLeft > 0 ) { // while there are still syllables left
var rando = Math.floor((Math.random()*300)); // draw a random word
if (sylls[rando] <= sylLeft) { // if this random word doesn't take too many syllables
haikuLine += words[rando] + " "; // add this to line string, add a space
sylLeft -= sylls[rando]; // subtract from syllables left
}
}
return haikuLine; // toss back finished line
}