JS:无法动态绑定事件



我在我的网站上有voting mechanism,如果用户试图vote(up or down),我会检查他是否登录,为此我编写了以下代码,

      $(".vote").click(function(){
         if(is_logged_in)
          {
             // Doing necessary stuff for vote up/down
          }else
            {
             // Showing Login Dialog box                        
            submitForm(".lform",function(response){
             if(data.status == "1")
               {
                 //Closing the Login Dialog Box
                 is_logged_in = 1;  // Assigning the value
                 bindEvent(".vote","click");  // Binding the Event,but can't able to it
               }
              });//Form Submission Closed
            }// Else Closed
         });// Main 'click' closed
     function bindEvent(selector,eventType){
         $(selector).bind(eventType);
        }

而不是外部功能bindEvent(".vote","click")我没有尝试过bindEvent(),但我无法在成功登录后动态绑定click event

为了在事件上绑定要发生的事情,您需要传递一个回调,以便在事件发生时触发。在上面的代码中,您没有指定回调。

function bindEvent(selector,eventType){
  $(selector).bind(eventType);
}

你需要这样写:

function bindEvent(selector,eventType,callBack){
  $(selector).bind(eventType, callBack);
}

你可以这样使用:

bindEvent('.target', 'click', function(){
  alert('This will trigger on click!');
})

更新

重读你的代码后,它看起来像你真正需要的是触发点击事件,而不是绑定一些东西给它:

$(".vote").click(function(){
  var $vote = $(this);
  if(is_logged_in) {
    // Doing necessary stuff for vote up/down
  }
  else {
    // Showing Login Dialog box                        
    submitForm(".lform",function(response){
      if(data.status == "1"){
        //Closing the Login Dialog Box
        is_logged_in = 1;  // Assigning the value
        $vote.click();
      }
    });//Form Submission Closed
  }// Else Closed
});
使用click()是一个简单的方法,或者你可以使用jQuery的.trigger('click')方法。您可能还希望避免click事件冒气泡到父元素,这在这种情况下是有意义的,因此您也可以使用.triggerHandler('click')来代替。

你应该使用on()来绑定动态创建的元素。

 $(document).on("click", ".vote",function(){
      if(is_logged_in)
      {
         // Doing necessary stuff for vote up/down
      }
      else
      {
         // Showing Login Dialog box                        
        submitForm(".lform",function(response){
         if(data.status == "1")
           {
             //Closing the Login Dialog Box
             is_logged_in = 1;  // Assigning the value
             bindEvent(".vote","click");  // Binding the Event,but can't able to it
           }
          });//Form Submission Closed
        }// Else Closed
});// Main 'click' closed

最新更新