Jquery中的多个Javascript函数

时间:2013-02-19 16:39:54

标签: javascript jquery ajax jquery-mobile

我很长一段时间都遇到过同样的问题,我想知道是否有人可以教我错误的做法。

我创建了一个多页Jquery(就像下面例子中的那个)但是,当我去添加对.js文件的引用时我已经保存了它总是倾向于不加载页面内容或者位置某处否则它根本就不会工作!

我的HTML代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <style>
        img.fullscreen {
            max-height: 100%;
            max-width: 100%;
        }
        </style>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
    $(document).on('pagebeforeshow', '#index', function(){
        $("#list").empty();
        var url="http://localhost/tmp/json4.php";
        $.getJSON(url,function(json){
            //loop through deals
            $.each(json.deals,function(i,dat){
                $("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
                $(document).on('click', '#'+dat.dealid, function(event){  
                    if(event.handled !== true) // This will prevent event triggering more then once
                    {
                        dealObject.dealID = $(this).attr('id'); 
                        dealObject.restaurantid = $(this).attr('data-restaurantid');
                        dealObject.shortName = $(this).find('h1').html(); 
                        dealObject.image = $(this).attr('data-image');
                        //dealObject.dname = $(this).find('input').html();
                        //dealObject.dname = $(this).find('desc').val();
                        dealObject.dealName = $(this).find('h6').html();
                        dealObject.description = $(this).find('h5').html(); 
                        //dataObject.dname=$(this).find('p').html()
                        //dealObject.name = $(this).find('desc').eq(0).val(dealObject.name);

                        $.mobile.changePage( "#index2", { transition: "slide"} );
                        event.handled = true;
                    }
                });            
            });
            $("#list").listview('refresh');
        });
    });

    $(document).on('pagebeforeshow', '#index2', function(){       
        //$('#index2 [data-role="content"]').html('You have selected Link' + dealObject.dname);
        $('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
        $('#index2 [data-role="content"]').find('#title').html(dealObject.name);
        //$('#index2 [data-role="content"]').find('#description').html(dealObject.dname);
                $('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
                $('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
                $('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);


    });

    var dealObject = {
        dealID : null,
        restaurantid : null,
        shortName : null,
        image : null,
        dealName : null,
        description: null
    }    
</script>

</head>     
<body>    
<div data-role="page" id="index">
    <div data-role="header" data-position="fixed">
        <h1>Current Deals</h1>
    </div>

    <div data-role="content">
        <div class="content-primary">
            <ul id="list" data-role="listview" data-filter="true"></ul>
        </div>
    </div>

    <div data-role="footer" data-position="fixed">
        <div data-role="navbar">
            <ul>
                <li><a href="http://localhost/findadeal/index.html" data-icon="home">Home</a></li>
                <li><a href="http://localhost/findadeal/mydeal.html" data-icon="grid">My Deals</a></li>
            </ul>
        </div>
    </div>
</div>

<!--New Page --> 
<div data-role="page" id="index2">
<!--<script src="js/ammend.js"></script>--!>
<div data-role="header">
        <h1> Find A Deal </h1> 
    </div>

    <div data-role="content">

 <!--       <?php
    if( !isset( $_SESSION ) ){
     session_start();
        }

    if( isset( $_SESSION['username'] ) ){
        echo ".";
        } ?>   --!>

        <form id="test">
        <label for="name">Deal Name:</label>
        <input type="text" value="" name="tname" id="tname"/>
        <label for="desc">Description</label>
        <input type="text" value="" name="desc" id="desc"/>  
        <a data-role="button" id="amend" data-icon="star" data-iconpos="left">Amend Deal </a>
        <input type="text" value="" name="dealid" id="dealid"/>

        <h3></h3>
        <!--<img src="" width="100px" height="100px" id="deal-img">
        <h1 id="title"></h1>
        <h3 id="description"></h3>
        <p id="name"></p>--!> 
    </div>

    <footer data-role="footer" data-position="fixed">
        <nav data-role="navbar">
            <ul>
                <li><a href="index.html" data-icon="home">Home</a></li>
                <li><a href="#index" data-icon="grid">My Deals</a></li>
            </ul>
        </nav>
    </footer>   
</div>
</body>
</html>

如果难以阅读,请道歉。这个javascript函数本身就可以正常工作。单击索引中的项目时,它会将您带到index2中的新页面。在索引2上有一个提交按钮,该按钮连接到引用<script src="js/ammend.js"></script>的文件。对于我来说这通常似乎是出错的地方,因为它们正在取消彼此,或者只是不合作。

该位置的js文件是:

$(document).on('pagebeforeshow', '#index2', function(){ 
$('#amend').on('click', function(){
    if($('#tname').val().length > 0 && $('#desc').val().length > 0 && $('#dealid').val().length > 0){
        userObject.tname = $('#tname').val(); // Put username into the object
        userObject.desc = $('#desc').val(); // Put password into the object
        userObject.dealid = $('#dealid').val();
        // Convert an userObject to a JSON string representation
        var outputJSON = JSON.stringify(userObject);
        // Send data to server through ajax call
        // action is functionality we want to call and outputJSON is our data
        ajax.sendRequest({action : 'index2', outputJSON : outputJSON});
    } else {
        alert('Please fill all nececery fields');
    }
 });    
});

$(document).on('pagebeforeshow', '#index2', function(){ 
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
    $.mobile.changePage( "#index2", { transition: "slide"} ); // In case result is true change page to Index  
}
$(this).find('[data-role="content"] h3').append('Deal Amended:' + userObject.name); // Change header with added message
//$("#index").trigger('pagecreate');
});

// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
    $.ajax({url: 'http://localhost/test/login/amend.php',
        data: save_data,
        async: true,
        beforeSend: function() {
            // This callback function will trigger before data is sent
            $.mobile.showPageLoadingMsg(true); // This will show ajax spinner
        },
        complete: function() {
            // This callback function will trigger on data sent/received complete
            $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
        },
        success: function (num) {
            if(num == "true") {
                $.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
            } else {
                alert('Deal has been added successfully'); // In case result is false throw an error
                $.mobile.changePage( "#index", { transition: "slide"} );
            }
            // This callback function will trigger on successful action
        },
        error: function (request,error) {
            // This callback function will trigger on unsuccessful action                
            alert('Error: " . mysql_error() . "Query: " . $query;');
        }
    });
}
}

// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
tname : "",
desc : "",
dealid: ""
}

当按下按钮时应该调用上面的内容,但是大多数时候我甚至无法进入看到按钮的阶段,一旦我将参考文献添加到此代码中。

如果有人之前遇到过与此问题相同的问题,或者能够解决问题,我会非常感激。

1 个答案:

答案 0 :(得分:1)

您的问题与jQuery Mobile页面处理有关。

因为您正在使用带有ajax的多个HTML页面进入DOM,所以必须从第一个HTML文件中引用所有js脚本。所有其他HTML文件只会部分加载,只会加载BODY部分,而HEAD将被丢弃。