Question

I'm starting to learn JQuery.

Right now I want to take the value from my paragraph and give it +1 everytime I click on it. This is what I've tried:

<body>
    <p>0</p>
    <script>
        $("p").click(function(){
            // code...
        });
    </script>
</body>

This is my script

Was it helpful?

Solution

You can do this as simple as this:

$(function(){ // you can wrap it here with in document ready block
   var i = 0;
   $("p").click(function(){
       $(this).html(i++);
   });
});

or may be a better one:

$(function(){ // you can wrap it here with in document ready block
   $("p").click(function(){
       $(this).html(+this.textContent + 1);
   });
});

Fiddle

OTHER TIPS

Try this:

  $( "p" ).click(function(){
     $(this).html(parseInt($(this).html(),10)+1);
  });

Working Demo

var count=0;
$( "p" ).click(function(){
    count++;    
    $(this).text(count);
});
this.firstChild.nodeValue = +this.firstChild.nodeValue + 1;

MOSR EFFICIENTS! :p

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top