Hello, please tell me how can you dynamically create and process elements? For example, here is the script for creating dynamic links.

success: function (data) { var res = ""; for (var i = 0; i < data.length; i++) { res += "Data " + data[i].Data + " "+ "<a id='"+i+"'"+"href=/api/admin/delete/"+data[i].ID+">Удалить</a>" + "<br />"; } console.log(key); $("#result").html(res); } 

And how now to process these links?

  $("??").click( function (e) { var href = $(this).attr('href'); ........ }); 
  • "<a class='linkClass' id='... $(".linkClass").click(... - Igor

3 answers 3

You can create either by inserting HTML code, or by creating elements and inserting them ( Node.appendChild ).

And you can handle in two ways:

  1. Add handler after creation (hardly suitable for HTML insertion).
  2. Delegation: listen to the events of not the elements, but the nearest ancestor. There, check for whom the event ( Event.target ) and call the handler for it.
    This is a good way to use it in most cases.

UPD:
Delegation Example:

 $(_ => { let root = $('#root'), inc = 0; // Динамическая добавка записей $('#addEntry').on('click', e => { root.append(`<div>Запись №${inc++}</div>`); }); // Второй аргумент - это CSS-путь обрабатываемых элементов root.on('click', 'div', function(e){ console.info(`Это обработчик записи с номером ${this.innerHTML.replace(/\D+/g, '')}`); }); }); 
 #root div{cursor: pointer;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='root'></div><hr /> <input type='button' id='addEntry' value='Добавить запись' /> 

  • And it is possible an example of delegation? - Nameless
  • @Nameless, UPD. - user207618

Use jQuery on method:

 $(document).ready(function() { var data = [{Data: 'data', ID: 1}, {Data: 'data2', ID: 2}]; var res = ""; for (var i = 0; i < data.length; i++) { res += "<a class='delete' id='"+i+"'>Удалить</a>" + "<br />"; } $("#result").html(res); /* ... */ $('body').on('click', 'a.delete', function(e) { e.preventDefault(); // отмена действия браузера по умолчанию console.log($(this).attr('id')); /* ... */ }); }); 

     function xxx() { event.preventDefault(); console.info("Link number: " + $(this).attr("id")) }; $("#add").click(function() { var res = ""; for (var i = 0; i < 3; i++) { res += "Data " + i + " " + "<a id='" + i + "' class='linkClass' href='http://google.com' >Удалить</a>" + "<br />"; } $("#result").html(res); $(".linkClass").on("click", xxx); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="add">Click me for add new link</button> <br> <span id="result"></span>