-4

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

Victor Bocharsky
  • 11,090
  • 12
  • 55
  • 88
user3406286
  • 59
  • 1
  • 2
  • 8

4 Answers4

2

Try this:

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

Working Demo

Milind Anantwar
  • 79,642
  • 23
  • 92
  • 120
2

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

Jai
  • 72,925
  • 12
  • 73
  • 99
1
var count=0;
$( "p" ).click(function(){
    count++;    
    $(this).text(count);
});
Brocco
  • 58,400
  • 10
  • 68
  • 76
Balachandran
  • 9,427
  • 1
  • 14
  • 25
0
this.firstChild.nodeValue = +this.firstChild.nodeValue + 1;

MOSR EFFICIENTS! :p

Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566