There is such code:

$('#block').change(function(){ var data = $('#block').data('prop'); FuncName(data); }); 

With one block everything works, but on the page you need to make a lot of such elements (the prop property will be different for everyone). How to make a handler in this case correctly in order to understand which of them switched? After all, the id of all blocks should be different.

    2 answers 2

    You can search for many elements like this: #id1, .class1 > div, a[data-id~="42"] .
    And inside the handler to work with this :

     // Создаём строку вида "#block1, #block2" и т. д. let idPool = Array(...Array(4)).map((_, i) => '#block' + ++i).toString(); // Обработчик, аргумент - элемент в жуквери-обёртке const handler = e => console.info(`data-id: ${e.data('id')}, value: ${e.text()}`); $(idPool).on('click', function(){ // this - DOM-элемент, оборачиваем его в жуквери (если нужно, конечно) handler($(this)); }); 
     div[data-id]{ padding: 5px; background: lightgreen; margin: 5px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='block1' data-id='42'>1</div> <div id='block2' data-id='24'>2</div> <div id='block3' data-id='22'>3</div> <div id='block4' data-id='44'>4</div> 


    Although, of course, it is more correct to combine the set of similar objects with a class.

      Change the id to class . We are happy.

       $('.block').change(function(){ var data = $(this).data('prop'); FuncName(data); }); 

      $(this) inside the handler points specifically to the very object on which the event occurred at the moment.


       $('.block').on('keyup', function(){ var data = $(this).data('prop'); FuncName(data); }); function FuncName(data) { console.log('my data prop = ' + data); } 
       .block { border: 1px solid black; margin: 10px; padding: 10px; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" data-prop="1" class="block" value="1"> <input type="text" data-prop="2" class="block" value="2"> <input type="text" data-prop="3" class="block" value="3"> 


       $('.block').change(function() { var data = $(this).data('prop'); FuncName(data); }); function FuncName(data) { console.log(data); } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="myradio" data-prop="allot" value="allot" checked="checked" class="block">Allot <input type="radio" name="myradio" data-prop="transfer" value="transfer" class="block">Transfer