【问题标题】:Javascript function called with button onclick, fails with onload使用按钮 onclick 调用的 Javascript 函数,因 onload 而失败
【发布时间】:2015-06-17 16:30:48
【问题描述】:

我正在尝试在 body 标记中使用外部 javascript 函数:

<!DOCTYPE html>

<script type="text/javascript" src="js/Long.min.js"></script>
<script type="text/javascript" src="js/ByteBufferAB.min.js"></script>
<script type="text/javascript" src="js/ProtoBuf.min.js"></script>
<script type="text/javascript" src="js/fs.js"></script>
<script type="text/javascript" src="js/bundle.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="cordova_plugins.js"></script>

</head>
<body onload ="heartbeat()">

<h2>A demo for showing the pub/sub between clients and the message     broker</h2> <h3>IoTGateway</h3>
Topic :
<input type="text" name="pub"/>
Message:
<input type="text" name="pub"/>
<button onclick="connect()">
    Connect
</button>
<br>
<button onclick="publish()">
    Publish
</button>
<br>

<h3>BluetoothID</h3> Topic:
<input type="text" name="sub"/>
<button onclick="heartbeat()">
    Subscribe
</button>
<br>
<p id = "test"></p>
<p id="sub"></p>
<script>
        function heartbeat() {
            alert("hello");
            try{
            MqttPlugin.subscribe({topic: "$EDC/plugin"});
            }
            catch(err){
            alert(err.message);
            }
        }
       /* try{
        MqttPlugin.heartbeat({topic: "$EDC/tum/B8:27:EB:A6:A9:8A/HEARTBEAT-V1/mqtt/heartbeat"});
        }
        catch(err){
        alert(err.message);
        }*/



        function publish() {

            MqttPlugin.publish({
            topic:"$EDC/plugin",
            data:"Mqtt data"

            });
        }

        function subscribe() {
            MqttPlugin.subscribe({topic: "$EDC/plugin"});
        }



</script>
</body>
</html>

当我使用事件 onclick 调用但因 onload 失败时调用了函数 heartbeat。在 onload 的情况下,它会抛出一个错误 MqttPlugin not defined。是不是因为调用函数的时候,js文件没有加载?有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你从未关闭过你的函数}
  • 你在哪里关闭函数和脚本标签?
  • 对不起,我还没有更新我的代码。我已经进行了这些更正。但是还是不行。
  • 引用插件的脚本标签在哪里?
  • 脚本标签是否包裹在head标签中?

标签: javascript html javascript-events


【解决方案1】:

我相信您在这里的基本目标是在页面加载时自动订阅主题。您可以尝试:

</script>
<style onload="heartbeat()"></style>
</body>

或者尝试改变导入的顺序。

第一个建议只是一个技巧,而不是一个完整的证明解决方案。

基本问题是在加载 cordova_plugins.js 之前调用 heartbeat 函数。因此,要么延迟函数调用,要么提前加载文件。

已编辑:

这个 jQuery 方法可能就是解决方案:

$( window ).load()

请查找文档here

【讨论】:

  • 完全正确。你是对的。在加载 js 文件之前调用的函数。有什么方法可以检查我的所有 js 文件是否已完全加载?
  • 您可能会发现this 很有用。还要检查 cmets。
  • 非常感谢。我认为这应该可以解决问题。会试一试。
猜你喜欢
  • 2014-06-05
  • 1970-01-01
  • 2014-12-22
  • 2015-04-27
  • 2015-05-14
  • 2019-11-06
  • 2021-11-30
  • 2013-02-09
  • 1970-01-01
相关资源
最近更新 更多