2015-09-24 43 views
2

我正在为需要动态刷新的网站上的div元素创建动态刷新功能。未重新绑定Jquery元素+ HTMLDivElement无法识别表达式

$(document).ready(function() { 

     function refreshDiv() { 
      var refreshUrl = window.location.pathname; 

      $('.refreshable').each(function() { 
       $(this).fadeOut("slow", function() { 
        $(this).hide().load(refreshUrl + " " + this, "").fadeIn("slow"); 
       }); 
      }); 
     } 

     $(document.body).on("click", ".login_button.submit", function(e) { 
      e.preventDefault(); 
      var username = $('#username').val(); 
      var password = $('#password').val(); 

      $.ajax({ 
       type : "POST", 
       url : '/login', 
       data : {username:username, password:password}, 

       success:function(response) { 
        if(response.status == 'success') { 

         $('#sb-site').animate({'opacity': '1'}, 300); 
         $('#login_form').toggle(); 
         refreshDiv(); 

        } else { 
         console.log('Something went wrong'); 
        } 
       }, 
       error:function(response) { 
        console.log('Something went wrong'); 
       } 
      }); 
     }); 

     $(document.body).on("click", ".logout_button", function(e) { 
      e.preventDefault(); 

      $.ajax({ 
       type : "POST", 
       url : '/logout', 

       success:function(response) { 

        if(response.status == 'success') { 
         refreshDiv(); 
        } else { 
         console.log('Something went wrong'); 
        } 

       }, 
       error:function(response) { 
        console.log('Something went wrong'); 
       } 
      }); 
     }); 
    }); 

我有几个问题出现了。

1)单击注销后,它会在/注销时调用Laravel控制器。之后,它会加载刷新内容的页面,但jquery点击事件不会重新绑定,所以我必须刷新才能在注销后再次登录。然而,登录后元素会重新变得良好。我想通过使用.on()会解决这个问题,但它没有。

2)元素被复制,因为我在执行'this'到refreshDiv函数时遇到了问题。我得到一个错误:

Uncaught Error: Syntax error, unrecognized expression: [object HTMLDivElement] 

这不会发生,如果我做

$(this).hide().load(refreshUrl + " .refreshable>*", "").fadeIn("slow"); 

,但我需要它单独加载每一个具体的有针对性的元素,或者重叠匹配类的内容。我想:

$(this).hide().load(refreshUrl + " " + this, "").fadeIn("slow"); 

我的首要目标就是能有一个可扩展的解决方案,只需添加一个.REFRESH类需要进行动态刷新的包装。

回答

0

如您在致​​的电话中所示,很难准确地从this中确定您想要的。您的错误显示的原因是因为您隐式地将this转换为字符串。其结果是"[object HTMLDivElement]"这使得你的电话看起来像这样

$(this).hide().load(refreshUrl + " " + "[object HTMLDivElement]", "").fadeIn("slow"); 

和为何出现错误应该清理。你需要从那个地方的div元素得到什么​​?

为了访问当前的div,只需使用propattr或本地调用从该点出得到的信息,如this.classNamethis.id$(this).data('location')

但是,因为你已经开始了这个链接关闭$(this),使得对.load的调用已经将refreshUrl中加载的内容应用于当前的this元素。

所以真的,所有你需要做的是

$(this).hide().load(refreshUrl,function(){ 
    $(this).fadeIn('slow'); // only fade in once content is loaded 
}); 

或者你想在这种情况下$(this).hide().load(refreshUrl).fadeIn("slow");将要使用的数据负荷,发生褪色。

+0

使用.attr只返回.refreshable,我只需要一个.refreshable类一次针对。 $(this)引用当前选定的div与该类;在这种情况下'.refreshable'。我明白为什么htmldivelement的东西现在不起作用。谢谢。我试着实现你的代码,但它似乎抛出一个错误,说主线程上的同步XMLHttpRequest被弃用,因为它对最终用户的体验有不利影响。另外,它似乎以某种方式破坏了我的X-CSRF。我不确定这是从哪里来的。 – austin43

相关问题