jQuery - .on()麻烦“点击”

时间:2012-05-28 17:57:00

标签: jquery

我正在尝试为我的jQuery / PHP创建一个事件,以便在向下滚动时加载更多内容。但是我遇到了一些关于我的.on()事件的麻烦。

我已经创建了一个函数(你看到下面的代码,我刚刚删除了函数functioname {}),当到达页面底部时调用它。

我的问题是,使用.on()你必须添加一个“点击”属性,这对我来说有点困难,因为它必须加载而不用点击。当我调用函数时,是否有一个属性使它运行.on()?

$("#container").on("click", ".box", function(event){
    alert("hej");

 $.post("site/scroll.php?mabid=" + $mabid,
  function(data){
    if (data != "") {
    alert($(".box:last").attr("mabid"));
    $(".box:last").after(data); 
  }
 });
});

我使用.on()的原因是因为它必须为新创建的元素添加一个jQuery插件,即 .box ,这使得它具有正确的布局。我试图绑定到新创建的dom元素的插件是:http://www.wookmark.com/jquery-plugin

更新

我没有加载内容的麻烦。我有麻烦将jQuery插件Wookmark添加到NEW DOM元素。这意味着它很乱,看起来非常糟糕。

请在他们的网站上阅读WookMark插件的小描述。这是一个插件,使 .box 在pinterest.com或wookmark.com上表现得相形见绌。

现在新的DOM元素只是插入并且看起来很乱,没有激活插件。

UPDATE2

经过一些沟通和误解后,只需将Wookmark插件添加到$ .post()中的新元素即可解决问题;像:

$.post("scroll.php?...", function(data){

  if(data != ""){
   //add the new dom elements, with .after(), .append() or something else.
   //add the needed effects to the new dom elements. For example with wookmark:
   $('.box').wookmark(//wanted effects); where .box is the dom elements I've created.
  }

});

感谢大家的帮助,特别是FelixKling和Oscar!

4 个答案:

答案 0 :(得分:0)

我不确定我是否正确使用它然而你知道你可以调用一个元素的.click(),就像执行$('.box).click()一样,就好像你点击了元素一样。

答案 1 :(得分:0)

jQuery“live”(已弃用)或“on”仅适用于click,dblclick,keydown,keypress,keyup,mousedown,mousemove,mouseout,mouseover和mouseup事件。

但是有一个解决方案,如果您只需要使用$('selector').on()$('selector').live()

使用此库:

LiveQuery: https://github.com/brandonaaron/livequery

$('selector').livequery(function(){
  // Here goes your on() logic.
});

答案 2 :(得分:0)

您正在寻找.scroll()事件。 试试这个:

$(window).scroll(function(e) {
     alert('window scroll');
     // write your fetching data part here
});

更新: 尝试自定义事件方法:

// bind the "applyWookmark" event 
$("#container").on("applyWookmark", ".box", function(event){
    // this will reapply the plugin
    $('.box').wookmark();
}); 

// after loading the data
// fire the custom event
$.post("site/scroll.php?mabid=" + $mabid,
    function(data){
    if (data != "") {
        alert($(".box:last").attr("mabid"));
        $(".box:last").after(data);  
        // fire event
        $('.box').trigger('applyWookmark');
    }
}

虽然没有测试过......

答案 3 :(得分:0)

一旦获得新数据,您似乎只需要将插件应用于新元素。

直接将它们应用于它们:

$(data).wookmark();

或者在将新数据添加到DOM后选择所有这些元素:

$('.box').wookmark();

那就是说,我不知道当你多次将插件应用到相同的元素时会发生什么。也许最好只将它应用于新元素。

相关问题