【问题标题】:Javascript function only works after a page-refreshJavascript 功能仅在页面刷新后有效
【发布时间】:2012-10-23 21:12:43
【问题描述】:

如果我单击“发送”按钮,则会在客户端 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()
  • 我看不出 jsfiddle 代码和我的代码之间没有区别,但是 jsfiddle 代码就像一个魅力。怎么会?
  • 另外,我删除了updateMessages(),好像是旧代码遗留下来的,不过还是需要刷新一下。
  • 您使用的是哪个浏览器?如果我将上述代码复制粘贴到 .html 文件中并在您定义的脚本标记之前加载 jquery 库,它在 Google Chrome 中可以正常工作...

标签: javascript function refresh


【解决方案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>

【讨论】:

  • 我错了,我删除数据库时还需要刷新,我不能有这个,因为新用户不应该刷新页面。检查此页面上某处的完整代码。有人可以修复完整的代码,以便在您删除数据库时(假装您是新用户)不必刷新页面?
  • 在 body onload 中添加这个 .. 像
  • 我添加了 "" 但是当我删除数据库时(假设你是新用户)我仍然需要先刷新页面。
【解决方案2】:

我将您的代码粘贴到测试文件中,并试图找出问题所在。我不知道确切的问题是什么,但我发现打击部分有一些问题,这就是为什么警报没有第一次出现:

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

尝试在上面的部分进行评论,警报将在不刷新页面的情况下起作用。我认为您应该检查一下您是否在上述部分中犯了错误。

【讨论】:

  • 确实这部分似乎是问题所在。但是,它需要在那里才能创建表。这部分需要更改什么以便创建表、显示警报并且我不需要刷新?我犯了什么错误?
  • 您在哪个浏览器中测试?由于只有 Chrome 和 Safari 支持访问 db 的方法。我已经在 Chrome 中对其进行了测试,并且警报消息第一次成功发送。我不需要刷新页面。
【解决方案3】:

如果复制粘贴到文件中的这段代码在 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 在同一目录中

【讨论】:

    【解决方案4】:

    我也在使用谷歌浏览器。我仍然需要先使用此代码进行刷新。

    <!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() 作为脚本标签内的最后一行...
    猜你喜欢
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2018-01-15
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多