Why is my jQuery trigger not working?

I'm just getting down to speed on jQuery, I apologize if this is a rookie bug.

I am trying to get a simple custom trigger to run without success and success. Maybe someone can help help and show me why this is not working.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>jQuery Trigger example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> $('#asset1').bind("triggerAssets", function() { alert('Assets'); }); </script> <script> $(document).ready(function(){ $('#asset1').trigger("triggerAssets"); }); </script> </head> <body > <div id="asset1" class="assets" >Asset <table> <tr> <td>Field One: </td> <td><input type="text" name="fieldOne" id="exfieldOne" value=""/></td> </tr> <tr> <td>Field Two: </td> <td><input type="text" name="fieldTwo" id="exfieldTwo" value=""/></td> </tr> <tr> <td>Field Three: </td> <td><input type="text" name="fieldThree" id="exfieldThree" value=""/></td> </tr> </table> </div> <hr> </body> </html> 
+4
source share
3 answers

Your anchor function will run until the page is displayed; #asset1 does not exist yet. Move it to the ready handler, which starts after the DOM is ready (and your element is present).

 $(document).ready(function(){ // wait until the DOM is ready, then do: $('#asset1').bind("triggerAssets", function() { alert('Assets'); }); $('#asset1').trigger("triggerAssets"); }); 
+5
source

you need to bind the event either when the DOM is ready, or add a delegate to future elements with asset1 identifier:

 $(document).ready(function(){ $('#asset1').bind("triggerAssets", function() { alert('Assets'); }); $('#asset1').trigger("triggerAssets"); }); 
0
source

If you need to do something before loading the page, define an object to handle things like:

  <script> var test = {}; $(test).bind("test", function(){ alert("Your trigger was fired!"); }); $(test).trigger("test"); </script> 
0
source

Source: https://habr.com/ru/post/1400866/


All Articles