Reputation: 27
I have to "Create a function, outside of the jQuery ready function, which increments the user's score when called and updates the HTML in span#score
. I have the Variable. I have the function started but am not sure how to finish it so that it will change the text. I'm also not sure that I'm calling the function right in my .ready
section.
I have this as part of a multiple question I put out a few days ago, but I really asked that wrong, too broad. I need to figure this out tonight. It's due at midnight but I'm sure he'll take it a little late. I think this is all the code I need to post. I think the rest would just be in the way, but let me know if you need it.
<script>
var mole='<img src="img/mole.jpg"/>';
var score=0;
$(document).ready(function(){
$("#score").click(increment);
}); //end.ready
function increment(){
score+=1
}; //end increment
</script>
Any help would be a true blessing at this point.
Upvotes: 0
Views: 2530
Reputation: 9102
Since the execution context inside the jQuery.click()
is set to individual DOM Element inside jQuery's elements array, you can also do something like this:
$(function() {
$('span#counter').on('click', increment);
// or $('span#counter').click(increment);
})
var score = 0;
function increment() {
this.innerHTML = ++score + '';
}
span#counter {
padding: 15px;
margin: 15px;
line-height: 10px;
cursor: pointer;
border: 1px solid #ddd;
user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span id="counter">0</span>
Upvotes: 0
Reputation: 50291
You need to return
the increased value from the function. Also use text
method to show the text in the DOM element
<!-- begin snippet: js hide: false console: true babel: false -->
var score = 0;
function increment() {
score += 1
return score;
};
$(document).ready(function() {
$("#score").click(function() {
var getIncreasedValue = increment();
$("#textDisplay").text(getIncreasedValue)
});
}); //end.ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textDisplay"></div>
<button id="score">Click</button>
Upvotes: 0
Reputation: 42304
Your increment()
function is indeed increasing the score; all you need to do is actually output this back on the page. This can be done with $("#score")[0].innerHTML = score
, as is seen in the following example:
var score = 0;
$(document).ready(function() {
$("#score").click(increment);
});
function increment() {
score += 1;
$("#score")[0].innerHTML = score;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">0</div>
The [0]
is needed because $(#score)
(although targeting an ID) returns a NodeList collection of objects, and you want to access the first object in this list.
Hope this helps! :)
Upvotes: 1