javascript - Updating Variable in HTML with JQuery -


i'm beginner programmer , i'm building game. whenever player clicks on gold image, should 1 gold. have following html piece of code:

<li id="gold">gold: 0</li> 

that's starting gold, , through jquery update with:

$('#gold-image').click(function() {     gold++;     $('#gold').replacewith('<li id="gold">gold: ' + gold + '</li>'); }); 

but don't feel that's best way update how gold player has. there way can write in html update variable whenever it's being changed or without having replace whole item?

later in game there many functions running @ same time , increasing gold number, think replacing html code not optimal way.

try existing div <div id="gold">gold: 0</div>:

$('#gold-image').click(function() {     gold++;     $('#gold').html('gold: ' + gold); }); 

although above code work. not use jquery this. there other frameworks way better such applications. example can take @ angularjs or ember.

the same functionality can achieved using two-way binding angularjs.

1) markup:

<div controller="gamectrl">   <img src="/path/to/img.png" ng-click="goldclicked()">   <div>gold {{ gold }}</div>   </div> 

2) javascript code

app.controller('gamectrl', function($scope) {   $scope.gold = 0;   $scope.goldclicked = function() {     $scope.gold += 1;   }; }); 

the code very simple , not need deal selectors. every time change gold (or other variable) automatically updated in dom. automatically modular code , dependency injection. in addition write declaratively , code easier read , easy change in future.

update: here working angularjs fiddle: http://jsfiddle.net/absolutemystery/7wgyk/


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -