简体   繁体   中英

Unable to bind click event to an echoed element

In JS I fire up a PHP script via XHR which is supposed to do:

 if($update)
    echo "<div class='popup'><div>(some text)</div></div>.";

echo "<script> $(document).ready(function() { $('.popup').bind('click', function() {   $('.popup').hide(); }); }); </script>"

I think I've tried everything, but there's no way I can make .popup hide after click. Where should I put .bind handler for this to work?

First add jQuery script to your JavaScript file which is common for all pages or whatever you want.

for eg:

// Put this to main.js script file
jQuery(document).on('click', 'div[data-rel=popup]', function(e){
  e.preventDefault();
  e.stopPropagation();
  $(this).hide();
});

And echo your HTML as:

if($update)
    echo "<div class='popup' data-rel='popup'><div>(some text)</div></div>.";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM