jquery events on non-present elements

后端 未结 2 787
小蘑菇
小蘑菇 2021-02-19 22:43

Is it bad to tie events to ids that aren\'t on the page in certain circumstances (based on PHP)? Will it cause code errors and slowness, or will jQuery automatically ignore them

2条回答
  •  情深已故
    2021-02-19 22:55

    $("selector") will always return a jquery object that has the list of elements that have matched your selector.

    if($("#nonexistantelement")) { /* this always happens*/ }
    

    Whatever is inside your if will always be true, because Objects are truthy. If you really wanted do that then you'd want to say something like:

    if($("#nonexistantelement").length > 0) { /* this only happens if you have something */ }
    

    That will tell you if you have actually matched to your elements. But there is no harm in just calling .click(function) on an empty jquery set. Because all jquery does is iterate over the elements matched by the selector and apply that listener. If there are no elements in the set, then it doesn't get applied, and as essentially a noop.

    Now if you want to bind callbacks to elements that dont exist yet, then look into .live() and delegate()

提交回复
热议问题