Problem description

When commenting on a handome topic, if it is a sub comment, there will be a @Someone The anchor link for.

Since the navigation at the top of the theme occupies a height of 50px, you must offset the original position 50px downward when clicking the anchor link to display it normally.

To this end, a solution was written earlier: The method of offset a certain position up and down after the anchor link jumps

However, for comments generated by ajax, If the page is not refreshed, clicking the anchor link on the left of the sub comment will not shift downward

That is, the previously written js does not work for dynamically generated page elements!

For a simple demo, see the following code:

 <html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("p").bind("click",function(){ $(this).slideToggle(); }); $("button").click(function(){ $("<p>This is a new paragraph.</p>"). insertAfter ("button"); }); }); </script> </head> <body> <div style="background-color:yellow"> <p>This is a paragraph</ p> <p>Please click any p element, it will disappear. Include this paragraph</ p> <button>Insert a new p element after this button</button> </div> </body> </html>

This code is very simple. There are two functions:

  1. Click the button to insert a <p> Label and its contents
  2. click P label The current p element will be hidden or displayed

But the problem with this code is:

Click the button to generate the p tag. If you click the generated p tag, you cannot hide or display the current p element.

What's the problem?

resolvent

The reason is that when the browser parses the js code, it will find all the p tags of the current page and bind each p tag with a related event (slideToggle()).

however Dynamic generation of p tags in the future However, the related event cannot be rebound again! Because js has been parsed by the browser

Here you can use the delegate() method.

We passed bind The bound click event is only applicable to the elements of the current page

use delegate The bound click event can be applied to Current or future elements (such as new elements created by scripts).

So the core code is changed to

 $(document).ready(function(){ $("div").delegate("p","click",function(){ $(this).slideToggle(); }); });

delegate The syntax of is:

 $(selector).delegate(childSelector, event,data,function)

In short, it refers to the specified element( selector )The child selector of, listens to some events, and binds related functions.

This bug will be solved in handhome v3.3.0

Reference article

Invalid click event when js dynamically loads HTML elements - He Ganlin - Blog Garden

Last modification: March 23, 2019
Do you like my article?
Don't forget to praise or appreciate, let me know that you accompany me on the way of creation.