Javascript click child element to add onclick to parent element will cause combo

Lionsure 2020-06-18 Original by the website

Web application requirements are diverse, and sometimes clicking an element(such as <span>delete</span>) requires adding a click event to its parent element using javascript; but directly adding an onclick event to its parent element will cause combo(such as double click), that is, the click event of its parent element will be executed immediately, which does not meet the requirement that the user clicks and then executes.

In order to avoid causing combo, deliberately try to use setTimeout to delay the execution of program, but it will still cause combo; logically, the click event added to its parent element will not be executed immediately, it is estimated that the child element and parent element coincide.

 

1. Javascript click child element to add onclick to parent element will cause combo(the click event of its parent element will be executed immediately)

For example, after clicking "Cancel", you need to delete the element <b></b>, and then add the click event to the parent element <span></span>, the specific code is as follows:

<div><span><b onclick="concer(this)">Cancel</b></span><div>

function concer(obj)
       {
              var span = obj.parentNode;
              span.innerHTML = "Delete";
              span.setAttribute("onclick","delete()");
       }

The delete() set for <span></span> in the above code will be executed immediately, forming a combo event. Originally, the delete() was required to execute after clicking "Delete" by user, but now it is automatically executed and does not meet the requirements.

 

2. The solution

Without deleting the parent element(<span></span>) of <b></b>, delaying the execution of the program will still cause combo, only delete <span></span> and then create a new one <span></span>, then add a click event(onclick) to it will not form a combo, it will not be executed immediately; because the original <span></span> no longer exists, the new <span></span> is no relationship with <b></b>. The specific code is as follows:

<div><span><b onclick="concer(this)">Cancel</b></span><div>

function concer(obj)
       {
              var span = obj.parentNode;
              parent = span.parentNode;
              parent.removeChild(span);

       var newSpan = document.createElement("span");
              newSpan.innerHTML = "Delete";
              newSpan.setAttribute("onclick","delete()");
       }