在ajax加载后运行javascript

时间:2013-03-26 16:09:10

标签: javascript jquery jquery-mobile jquery-mobile-pageshow

我有一个小的javascript函数,我试图通过JQM ajax加载页面后运行。现在我已经看过其他帖子讨论这个问题,但还是无法解决我的问题。当我的索引加载认为它会在DOM更改后保持在头部但是它仍然没有做任何事情时,我最初加载了脚本。继承剧本。

$(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

2 个答案:

答案 0 :(得分: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 。< / p>

答案 1 :(得分:1)

建议不要

bind。请改用on

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

  

从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。对于早期版本,.bind()方法用于将事件处理程序直接附加到元素。处理程序附加到jQuery对象中当前选定的元素,因此这些元素必须存在于调用.bind()的位置。有关更灵活的事件绑定,请参阅.on()或.delegate()

中对事件委派的讨论