How to write here url considering el on the way to page 1-2-3 ...

function picdown(num) { [1,2,3,4,5,6].forEach(function(el) { if (el === num) { var msg = $('.pic' + el).serialize(); $.ajax({ type: 'POST', url:'/ajax/pic1.html' , data: msg, success: function(data) { $('.pic' + el).html(data); }, error: function(xhr, str){ alert('ошибка: ' + xhr.responseCode); } }); } }); } jQuery('.cp1').click(function() {picdown(1)}); jQuery('.cp2').click(function() {picdown(2)}); jQuery('.cp3').click(function() {picdown(3)}); jQuery('.cp4').click(function() {picdown(4)}); jQuery('.cp5').click(function() {picdown(5)}); jQuery('.cp6').click(function() {picdown(6)}); 

thank

    1 answer 1

    try to think not for each specific case, but generally. Your actions are of the same type. There are 6 elements, and you write 6 lines for hanging handlers. Further in the cycle you compare the number for 6 elements.
    Ask yourself whether it can be done in one function? Probably because you can, if the initial element will store information about the index?

     <a href="#" class="cp cp1" data-idx="1"> <a href="#" class="cp cp2" data-idx="2"> 

    Ok, now to the general cp class, hang a single handler that will retrieve data-idx for the element:

      $(".cp").click(function(){ var idx = $(this).data('idx'); var $p = $(".pic" + idx); $p.load("/ajax/pic" + idx + ".html", $p.serialize() ); }); 
    • You can also use the option with - what? :) - Grundy
    • Thanks, everything works - abooks abooks
    • @Grundy: D was first $.post , and wanted to add about $.load :) - teran