JavaScript函数只有在页面刷新后才能生效

3
如果我点击“发送”按钮,一条消息将被放置在客户端的SQL数据库中,并显示通知。
但是,只有在我刷新页面后才能正常工作!
如何使函数立即开始工作?我已经尝试将“addMessage”函数放置在$(document).ready(function()中,但是函数完全停止工作。请参见下面的代码:
<script>
        var db;

        $(document).ready(function()    {
            //Opens the database
            try
            {
              if (!window.openDatabase) {
                    alert('Not supported -> Please use a webkit browser');
              } else {
                  var shortName = 'Rvpk';
                  var version = '1.0';
                  var displayName = 'The Rvpk databse';
                  var maxSize = 3072*1024; //  = 3MB in bytes 65536
                  db = openDatabase(shortName, version, displayName, maxSize);      
                  }  
            }
            catch(e)
            {
              if (e == 2) {
                  alert("Invalid database version.");
              } else {
                  alert("Unknown error "+e+".");
              }return;
            }

            //If needed creates the messagetable
            db.transaction(function (tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
            });
        });

        //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
        function addMessage(){
        var message = $('input:text[name=message]').val();

            db.transaction(function (tx) {
                     tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
            });
            console.log("Message "+ message +" added to database");

            //Shows a notification that sending the message was a success
            alert('The message has been sent');

            //Update the messages
            updateMessages();            
        }    
    </script>
    </head>

    <body>
    <?php include("includes/header2.php"); ?>

                <div data-role="content">
                    <form>
                        <fieldset>
                            <label id="messagelabel" for="message">Message:</label>
                            <input id="message" type="text" name="message" value="This can't go on like this">
                            <button onClick="addMessage()" data-theme="g">Send</button>
                        </fieldset>
                    </form>
                </div> 

你没有定义updateMessages()。 - Mudassir Ali
请查看此链接:http://jsfiddle.net/JkTbT/ - Mudassir Ali
我看不出jsfiddle代码和我的代码有什么区别,但是jsfiddle代码却能够完美运行。为什么呢? - t0byman
另外,我删除了updateMessages()函数,似乎这是旧代码的残留物,但我仍然需要刷新。 - t0byman
你使用哪个浏览器?如果我将上述代码复制粘贴到一个 .html 文件中,并在你定义的脚本标签之前加载 jQuery 库,它在 Google Chrome 中可以正常工作。 - Mudassir Ali
4个回答

1
请尝试以下操作:
document.ready仅在页面加载时运行。 相反,将其用于单独的函数,并在需要时调用该函数。 复制并粘贴以下脚本。
<script>
        var db;

        function runThis()
        {
            //Opens the database
            try
            {
              if (!window.openDatabase) {
                    alert('Not supported -> Please use a webkit browser');
              } else {
                  var shortName = 'Rvpk';
                  var version = '1.0';
                  var displayName = 'The Rvpk databse';
                  var maxSize = 3072*1024; //  = 3MB in bytes 65536
                  db = openDatabase(shortName, version, displayName, maxSize);      
                  }  
            }
            catch(e)
            {
              if (e == 2) {
                  alert("Invalid database version.");
              } else {
                  alert("Unknown error "+e+".");
              }return;
            }

            //If needed creates the messagetable
            db.transaction(function (tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
            });
        }

        //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
        function addMessage(){

        //call db access function.
        runThis();

        var message = $('input:text[name=message]').val();

            db.transaction(function (tx) {
                     tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
            });
            console.log("Message "+ message +" added to database");

            //Shows a notification that sending the message was a success
            alert('The message has been sent');

            //Update the messages
            updateMessages();            
        }    
    </script>

我错了,当我删除数据库时仍然需要刷新,但是新用户不应该这样做。请在此页面的某个地方检查完整代码。有人能修复完整的代码吗,以便当您删除数据库(假装您是新用户)时,无需刷新页面? - t0byman
将此代码添加到 body 的 onload 中,如:<body onload="runThis();">。 - suresh gopal
我添加了"<body onload="runThis();">",但是当我删除数据库(假装你是一个新用户)时,我仍然需要先刷新页面。 - t0byman

0

如果将此代码复制并粘贴到文件中,在Chrome中打开时可以正常工作,点击按钮后会弹出一个警报消息"消息已发送",无需刷新即可。

<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script>
          var db;

          $(document).ready(function()    {
              //Opens the database
              try
              {
                if (!window.openDatabase) {
                      alert('Not supported -> Please use a webkit browser');
                } else {
                    var shortName = 'Rvpk';
                    var version = '1.0';
                    var displayName = 'The Rvpk databse';
                    var maxSize = 3072*1024; //  = 3MB in bytes 65536
                    db = openDatabase(shortName, version, displayName, maxSize);      
                    }  
              }
              catch(e)
              {
                if (e == 2) {
                    alert("Invalid database version.");
                } else {
                    alert("Unknown error "+e+".");
                }return;
              }

              //If needed creates the messagetable
              db.transaction(function (tx) {
                   tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
              });
          });

          //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
          function addMessage(){
          var message = $('input:text[name=message]').val();

              db.transaction(function (tx) {
                       tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
              });
              console.log("Message "+ message +" added to database");

              //Shows a notification that sending the message was a success
              alert('The message has been sent');

              //Update the messages
              updateMessages();            
          }    
      </script>
      </head>

      <body>
      <?php include("includes/header2.php"); ?>

                  <div data-role="content">
                      <form>
                          <fieldset>
                              <label id="messagelabel" for="message">Message:</label>
                              <input id="message" type="text" name="message" value="This can't go on like this">
                              <button onClick="addMessage()" data-theme="g">Send</button>
                          </fieldset>
                      </form>
                  </div> 
</body>
</html>

当然,确保在同一目录中有jquery.min.js


0

我也在使用Google Chrome。但我仍需要使用以下代码先进行刷新。

<!DOCTYPE html>
<html lang="nl">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="jquery.mobile-1.2.0/jquery.mobile-1.2.0.css" />
    <script src="jquery.mobile-1.2.0/jquery-1.8.2.min.js"></script>
    <script src="jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.js"></script>

    <link href="css/layout.css" rel="stylesheet" type="text/css" />
    <link rel="shortcut icon" href="afbeeldingen/favicon.ico" type="image/x-icon" />
    <meta name="Author" content="Tobias Boekwijt" />    <title>This can't go on like this</title>

<script>
var db;

        function runThis()
        {
            //Opens the database
            try
            {
              if (!window.openDatabase) {
                    alert('Not supported -> Please use a webkit browser');
              } else {
                  var shortName = 'Rvpk';
                  var version = '1.0';
                  var displayName = 'The Rvpk databse';
                  var maxSize = 3072*1024; //  = 3MB in bytes 65536
                  db = openDatabase(shortName, version, displayName, maxSize);      
                  }  
            }
            catch(e)
            {
              if (e == 2) {
                  alert("Invalid database version.");
              } else {
                  alert("Unknown error "+e+".");
              }return;
            }

            //If needed creates the messagetable
            db.transaction(function (tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
            });
        }

        //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
        function addMessage(){

        //call db access function.
        runThis();

        var message = $('input:text[name=message]').val();

            db.transaction(function (tx) {
                     tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
            });
            console.log("Message "+ message +" added to database");

            //Shows a notification that sending the message was a success
            alert('The message has been sent');        
        }    
</script>
</head>
<body>
    <div id="wrapper">
        <div data-role="page" id="page1">
            <div data-role="header" data-position="fixed" data-theme="a">                
                <h3>Test</h3>

                <a href="#popupInfo" data-rel="popup" data-position-to="window" data-role="button" data-icon="grid" data-iconpos="notext" class="ui-btn-right" data-theme="a" data-transition="pop"></a>
                    <div data-role="popup" id="popupInfo" class="ui-content" data-theme="e">
                    <a href="#" data-rel="back" data-role="button" data-theme="bl" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>
                      <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
                            <a data-role="button" href="messages.php" data-theme="b">My messages</a>
                            <a data-role="button" href="logout.php" data-theme="r">Log out</a>
                      </div>
                    </div>

                <a data-role="button" href="for_who.php" data-icon="home" data-iconpos="notext" class="ui-btn-left" data-theme="a"></a>
            </div> 

            <div data-role="content">
                <form>
                    <fieldset>
                        <label id="messagelabel" for="message">Message:</label>
                        <input id="message" type="text" name="message" value="This can't go on like this">
                        <button onClick="addMessage()" data-theme="g">Send</button>
                    </fieldset>
                </form>
            </div> 
        </div>    
    </div>
</body>
</html>

你在哪里加载主要的jQuery库?如果你不想使用jQuery,那么请在脚本标签内添加window.onload = runThis()作为最后一行... - Mudassir Ali

0
我把你的代码粘贴到测试文件中,试着找出确切的问题。虽然不知道确切的问题所在,但我发现下面一部分存在问题,这就是为什么警报第一次不会出现的原因:

db.transaction(function (tx) { tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]); });

尝试注释掉上面的部分,警报将在不刷新页面的情况下正常工作。我想你应该检查上述部分是否出现错误。

似乎这部分是问题所在。但是,它需要存在才能创建表格。这部分需要怎样的更改才能创建表格,显示警报而无需刷新?我犯了什么错误? - t0byman
你在用哪个浏览器测试?因为访问数据库的方法只支持Chrome和Safari。我已经在Chrome中进行了测试,警报消息第一次成功出现。我不需要刷新页面。 - Dhaval

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接