简体   繁体   English

为什么我的jQuery触发器不起作用?

[英]Why won't my jQuery trigger work?

I'm just coming up to speed on jQuery, I'll apologize up front if this is a rookie error. 我只想加快jQuery的速度,如果这是一个菜鸟错误,我会在前面道歉。

I'm attempting to get a simple custom trigger to fire without and success. 我试图让一个简单的自定义触发器在没有成功的情况下触发。 Maybe someone can help help out and show me why this isn't 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>

Your binding function will run before the page is rendered; 您的绑定功能将在呈现页面之前运行; #asset1 doesn't yet exist. #asset1尚不存在。 Move it into the ready handler, which fires after the DOM is ready (and your element is present). 将其移动到ready处理程序中,该处理程序在DOM准备就绪触发(并且您的元素存在)。

$(document).ready(function(){ // wait until the DOM is ready, then do:

  $('#asset1').bind("triggerAssets", function() {
    alert('Assets');
  });

  $('#asset1').trigger("triggerAssets");

});

you need to bind the event either when the DOM is ready or add a delegate on future elements with id of asset1: 您需要在DOM准备就绪时绑定事件,或者在id为asset1的future元素上添加委托:

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

    $('#asset1').trigger("triggerAssets");
});

If you need to do something before the page is loaded, define an object to handle things like: 如果您需要在加载页面之前执行某些操作,请定义一个对象来处理以下内容:

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

            $(test).trigger("test");

    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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