Right now I have this code:

$("#1").click(function() { load(0); return false; }); $("#2").click(function() { load(1); return false; }); 

I need something like this:

 $("#peremennaya").click(function() { peremennaya1 = peremennaya - 1; load(peremennaya1); return false; }); $("#peremennaya").click(function() { peremennaya1 = peremennaya - 1; load(peremennaya1); return false; }); 

That is, to catch clicks of links from the ID # number to do the calculation - 1, and load them by calling the load function (the number that has been calculated);

If someone does not understand, I need variables like this:

 RewriteRule ^page/([0-9])$ index.php?mode=pages&id=$1 
  • Clicks to catch everything at all, on all elements of the page, or is there some kind of class? - Sergiks

3 answers 3

The variable is the id clicked item.

It is necessary to catch all the clicks in general, to see whether the id element you clicked is a number, and then perform your actions. It is better to somehow narrow the catch of clicks to the elements of a single class, or inside one parent.

 $(document.body).on('click', function(e) { var id = parseFloat(e.target.id); if( !( !isNaN(e.target.id) && (id | 0) === id)) return; // не число load( --id); return false; }); 

Determining whether an id is a number is taken from here .


In general, you'd better change the markup . Give all clickable elements the general class by which to distinguish them, and write the values ​​for the load in the date attribute:

 $('.load').on('click', function(){ var n = $(this).data('n'); load( n-1); return false; }); var data = ['AAA','BBB','CCC']; function load( m) { $('#out').text(data[m]); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="load" href="#" data-n="1">A</a> <a class="load" href="#" data-n="2">B</a> <a class="load" href="#" data-n="3">C</a> <div id="out"></div> 

     $("#2").click(function() { load(--this.id); return false; }); 

    check

      If the variable contains not only numbers but letters for example: id = "myId5"; That will help out the concatenation of the string in the argument when calling jquery. Those:

        $("#myId5").click(function() { //Берем id элемента и отделяем от него число, если числа двузначные то нужно либо сделать все числа двузначными или воспользоваться регулярными выражениями var a = ($(this).attr("id")).slice(0,-1); // Преобразуем полученное число как нам нужно и вызываем необходимую функцию сложив строки в аргументе a = parseInt(a) - 1; load("myId" + a); return false; }); 
      • in the example: attr("id") -> "2" , and if you take .slice(0,-1) from this line .slice(0,-1) you end up with an empty string. - Grundy
      • That's right, I wrote it for the cases when id contains not only numbers (example: id = "myId5";), but did not change the code. Thank. - Deum