JavaScript implements dynamically added elements to add click events

Keywords: Javascript Front-end html5

In the process of page development, it is often necessary to dynamically add elements and bind related events to this element. In this case, it is generally necessary to add related attributes to the elements and then write the event functions of these elements. How do dynamically added elements bind events?

Native JavaScript

There are two main ways to implement native JavaScript. The first is to add an oclick event to the dynamically added html code, and then pass a unique parameter to judge which is clicked, and then do the corresponding operation.  

The second is to handle it through the principle of event delegation. Event delegation actually binds an event listener to the whole container, and then each list item can be accessed after being clicked, which is more efficient.

The specific code implementation is as follows:

First: onclick

<body>  <button onclick="AddJob()">Add work experience</button>  <button onclick="GetJobs()">Get all work</button>   <div id="joblist">    <div id="job1" class="job">      <input name="CompanyName" type="text" value="Company 1" />      <button onclick="DelJob(1)">delete</button>    </div>  </div>  <script type="text/JavaScript">    //Add work experience function AddJob() {var timestamp = parseInt((new Date()).valueOf()); / / unique identifier console.log (parseInt ((New date()). Valueof()); document.getelementbyid ("joblist"). InnerHTML + = ` < div id = "job ` + timestamp + `" class = "job" > < input name = "CompanyName" type = "text" value = "company ` + timestamp + `" />< button onclick = "deljob (` + timestamp + `)" > delete < / button > < / div > `;} / / delete work experience function deljob (timestamp) {document.getelementbyid ("job" + timestamp). Remove();} / / get all work experience function getjobs() {var jobs = document.getelementbyclassname ("job"); VAR arr = []; for (var i = 0; i < jobs.length; i++) {        var job = jobs[i];        var companyName = job.children[0].value;        arr.push(companyName);      }      console.log(arr);      alert(arr);    }</script></body>

The second addEventListener:

document.getElementById('joblist').addEventListener('click', function (ev) {    var target = ev.target || ev.srcElement;    if (target.nodeName.toLowerCase() == 'button') {      var e = document.getElementById(target.parentNode.id);      document.getElementById("joblist").removeChild(e);    }});

jquery implementation

Starting from jQuery 1.7, you should use on. The syntax is as follows:

 
$(staticAncestors).on(eventName, dynamicChild, function() {});

Explanation:

This is called an event delegate and works as follows. The event is attached to the static parent of the element that staticprocessors should handle(  ).

This jQuery handler is triggered every time an event is triggered on this element or one of its descendants.

The handler then checks whether the element that triggered the event matches your selector (dynamicChild). When it matches, your custom handler function will be executed.

Before that, the recommended method is to use live():

 
$(selector).live( eventName, function(){} );

However, live() was deprecated as on() in 1.7 and completely deleted in 1.9.

 
$(selector).live( eventName, function(){} );

You can replace it with the following on() method:

 
$(document).on( eventName, selector, function(){} );

For example, if your page uses class names to dynamically create elements, dosomething will bind events to existing parents (this is the core of the problem here. You need to bind to existing things, not to dynamic content). This can be (and the simplest option) document. Although remember that document may not be the most effective choice.

 
$(document).on('mouseover mouseout', '.dosomething', function(){    // what you want to happen when mouseover and mouseout     // occurs on elements that match '.dosomething'});

Any parent that exists when the event is bound can. For example

 
$('.buttons').on('click', 'button', function(){    // do something here});

Will apply to

<div>    <!-- <button>s that are generated dynamically and added here --></div>

End of this article

Posted by ldougherty on Sun, 24 Oct 2021 16:12:01 -0700