Adi*_*rti 3 html javascript jquery function-calls
我在使用click事件处理程序执行函数时遇到问题。如果我摆脱了函数numberCheck()并将代码直接发布到事件处理程序中,那么它将正常工作。我在这里缺少基本的东西吗?
这是我的代码:
jQuery(document).ready(function(){
var scopedVariable;
var number = Math.floor(Math.random()*11);
function numberCheck() {
$(this).closest('#outsideContainer').find('.hotter').addClass('hideStuff');
$(this).closest('#outsideContainer').find('.colder').addClass('hideStuff');
var guess = $(this).closest('#guessContainer').find('.value').val();
if( +guess === number)
{
$(this).closest('#outsideContainer').find('.gotIt').removeClass('hideStuff');
}
else {
$(this).closest('#guessContainer').find('.value').val('Please guess again');
if(Math.abs(guess - number) < Math.abs(scopedVariable - number)) {
$(this).closest('#outsideContainer').find('.hotter').removeClass('hideStuff');
}
else if(Math.abs(guess - number) > Math.abs(scopedVariable - number)) {
$(this).closest('#outsideContainer').find('.colder').removeClass('hideStuff');
}
scopedVariable = guess;
}
}
$('.query').on('click', function() {
numberCheck();
});
});
Run Code Online (Sandbox Code Playgroud)
如果需要,这是我的HTML:
<body>
<div id="outsideContainer">
<div id="guessContainer">
<h3> Guess a number between 1 and 10 </h3>
<input id="txtfield" name="txtfield" type="text" class="value"/><br>
<input type = "submit" class="query" />
</div>
<div id="guessShow">
<p class="hotter hideStuff" > Getting Hotter!! </p>
<p class="colder hideStuff"> Getting Colder, BRRR!!! </p>
<p class="gotIt hideStuff"> Awesome! You have guessed the number </p>
</div>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
任何帮助对此非常感谢。
Try passing this to your function (numberCheck(this)) and then name the parameter in your function something else and change the instances of this in the function to that name, like so:
function numberCheck(submitButton) {
$(submitButton).closest('#outsideContainer').find('.hotter').addClass('hideStuff');
[...]
}
$('.query').on('click', function() {
numberCheck(this);
});
Run Code Online (Sandbox Code Playgroud)