2013-03-26 125 views
0

我有一个小的JavaScript函数,我试图让页面通过JQM ajax加载加载后运行。现在我已经看到其他文章讨论这个问题,但一直没能解决我的问题。当我的索引加载时,我最初加载了脚本,认为它会在DOM更改后保留在头部,但它仍然没有任何作用。这是剧本。
ajax加载后运行javascript

$(function(){ 
    var $product = $('#product'), 
     $imgs = $product.find(".child"), 
     imageTotal = $imgs.length - 1, 
     clicked = false, 
     widthStep = 20, 
     currPos, 
     currImg = 0, 
     lastImg = 0; 
    $imgs.bind('mousedown', function (e) { 
     e.preventDefault(); // prevent dragging images 
    }) 
     .filter(':gt(0)').addClass('notseen'); 

    $product.bind('mousedown touchstart', function (e) { 
     if (e.type == "touchstart") { 
      currPos = window.event.touches[0].pageX; 
     } else { 
      currPos = e.pageX; 
     } 
     clicked = true; 

    }); 
    $(this) 
     .bind('mouseup touchend', function() { 
     clicked = false; 
    }) 
     .bind('mousemove touchmove', function (e) { 
     if (clicked) { 
      var pageX; 
      if (e.type == "touchmove") { 
       pageX = window.event.targetTouches[0].pageX; 
      } else { 
       pageX = e.pageX; 
      } 
      widthStep = 20; 
      if (Math.abs(currPos - pageX) >= widthStep) { 
       if (currPos - pageX >= widthStep) { 
        currImg++; 
        if (currImg > imageTotal) { 
        currImg = 0;} 
       } else { 
        currImg--; 
        if (currImg < 1) { 
         currImg = imageTotal; 
        } 
       } 
       currPos = pageX; 
       $imgs.eq(lastImg).addClass('notseen'); 
       $imgs.eq(currImg).removeClass('notseen'); 
       lastImg = currImg; 
       // $obj.html('<img src="' + aImages[options.currImg] + '" />'); 
      } 
     } 
    }); 
}); 

document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false);// JavaScript Document 

我加载它使用标准<script>标签,我所知道的是这个问题,我只是不知道如何解决它。

我使用jQuery Mobile的1.3和jQuery 1.9.1

回答

3

如果要加载的东西后,jQuery Mobile的页面加载,你需要使用适当的jQuery Mobile的页面事件,像pageshow执行。

下面是一个例子:

$(document).on('pageshow', '#index', function(){  
    alert('Page loaded'); 
}); 

而这里的工作的例子:http://jsfiddle.net/Gajotres/tuJEm/

你应该把你的代码pageshow事件中。 #index应该是您网页的ID。

如果您想了解更多关于jQuery Mobile的页面事件来看看这个ARTICLE,或者发现它HERE

1

bind不推荐使用。改为使用on

http://api.jquery.com/bind/

在jQuery 1.7中,。对()方法是用于事件处理程序安装到一个文件的优选方法。对于早期版本,.bind()方法用于将事件处理程序直接附加到元素。处理程序被附加到jQuery对象中当前选定的元素上,所以这些元素必须存在于对.bind()的调用发生时。有关更灵活的事件绑定,请参阅.on()或.delegate()中的事件委托的讨论。