我很困惑。我已经使用了这个jquery功能一段时间了,它在这里不起作用。它返回正确的值并打印到控制台,但它不会在页面加载时附加数据。
HTML:
<div class="row">
<div class="col-xs-12">
<span>Press any key to get started!</span>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<span>Wins</span>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div>Current word: </div>
<br>
<div class="currentWord"></div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<span class="guessRem">Number of guesses remaining:</span>
</div>
</div>
JS:
var hangmanWords = ["baseball", "programming", "movies", "america", "lakers", "gardening"];
var wins = 0;
var remainingGuesses = 12;
function selectAWord (){
var randomVal = hangmanWords[Math.floor(Math.random() * hangmanWords.length)].toString();
$(".currentWord").append(randomVal);
$('.guessRem').append(remainingGuesses);
console.log(randomVal);
return (randomVal);
}
selectAWord();
答案 0 :(得分:2)
尝试使用ready函数,以便DOM完全加载,.currentWord/.guessRem
的元素.append
就在那里:
$(function(){
//Your function call here
selectAWord();
})
希望这有帮助。
$(function(){
selectAWord();
})
function selectAWord (){
var hangmanWords = ["baseball", "programming", "movies", "america", "lakers", "gardening"];
var wins = 0;
var remainingGuesses = 12;
var randomVal = hangmanWords[Math.floor(Math.random() * hangmanWords.length)].toString();
$(".currentWord").append(randomVal);
$('.guessRem').append(remainingGuesses);
console.log(randomVal);
return (randomVal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-12">
<span>Press any key to get started!</span>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<span>Wins</span>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div>Current word: </div>
<br>
<div class="currentWord"></div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<span class="guessRem">Number of guesses remaining:</span>
</div>
</div>