javascript - 将对话框函数包装在 deviceReady 事件监听器中后未定义

标签 javascript android cordova phonegap

我编写了一个简单的应用程序来测试 native 对话框。为简单起见,我将仅包含用于触发警报对话框的代码。这是代码:

index.html

<div id="alert" class="item">
  <h1>Alert</h1>
  <p>Title</p>
  <input type="text" />
  <p>Message</p>
  <textarea></textarea>
  <p>Button label</p>
  <input type="text" />
  <button onclick="alertDiag()" class="submit">GO</button>
</div>

ma​​in.js

window.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  function alertDiag() {
    var message = document.getElementById("alert").children[4].value;
    var title = document.getElementById("alert").children[2].value;
    var buttonName = document.getElementById("alert").children[6].value;
    function alertCallback() {
      alert("The alert was dismissed");
    }
    navigator.notification.alert(message, alertCallback, title, buttonName);
  }
}

config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.nativedialogues" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
  <name>Testing Native Dialogues</name>
  <description>
    An application for testing native dialogues
  </description>
  <author email="example@gmail.com" href="http://www.example.com">
    PhoneGap Team
  </author>
  <content src="index.html"/>
  <preference name="DisallowOverscroll" value="false"/>
  <access origin="*"/>
  <plugin name="cordova-plugin-dialogs" spec="~1.3.4"/>
</widget>

但是,由于 alertDiag() 封装在 deviceReady 事件监听器中,因此通过单击按钮调用时它是未定义的。在控制台中我收到以下错误:

Cannot get property 'alert' of undefined

如何才能使该功能仅在设备准备就绪后可用,但同时能够在单击按钮时执行它?

我使用phonegap云构建服务来打包应用程序,而不是本地phonegap cli。

最佳答案

首先,正如您可能已经了解的那样,deviceready 是 Cordova 完成加载应用程序的所有插件时触发的事件。这只是一个指示,让您知道如果有一个逻辑可以在页面加载时访问任何插件,那么理想情况下它应该进入设备就绪回调内部。

在您的情况下,alertDiag() 是在用户交互时调用的,而不是在页面加载时调用的。这意味着您需要在 deviceready 回调之外定义它。

window.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  // any logic on page load
}

function alertDiag() {
  var message = document.getElementById("alert").children[4].value;
  var title = document.getElementById("alert").children[2].value;
  var buttonName = document.getElementById("alert").children[6].value;

  function alertCallback() {
    alert("The alert was dismissed");
  }
  navigator.notification.alert(message, alertCallback, title, buttonName);
}

关于javascript - 将对话框函数包装在 deviceReady 事件监听器中后未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409599/

相关文章:

java - 禁用在 ViewPager 中的某些 fragment 上滑动

android - 无法在命令行中运行 android 命令

ios - 适用于 iOS 的 Cordova 文件选择器?

javascript - ionic 应用程序无法识别 Android 手机中的语音

javascript - 检查数字是否在范围内或超出范围

javascript - 匿名函数和命名函数的疑问

javascript - 在全局/根坐标中确定 SVG 视口(viewport)

android - 在使用 Retrofit 和 Room 时,我是否需要提及协程调度程序?

java - 我如何更改另一个 Activity 的共享偏好值?

javascript - For 循环内的闭包