【问题标题】:Function not running on button click on phonegap功能未在按钮单击phonegap上运行
【发布时间】:2015-11-21 13:51:57
【问题描述】:

我有以下 HTML:

...

</head>
<body>
    <div class="app">
        <h1>Match It!</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
        </div>
    </div>
    <button id="camera">take a pic</button>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</body>

...

我正在尝试在单击 ID 为 camera 的按钮时打开相机。

我在 index.js 中有以下 JavaScript:

var app = {

    ...

    cameraUse: function() {
        navigator.camera.getPicture(function(imagePath){
            document.getElementById("photoImg").setAttribute("src", imagePath);
        }, function(){
            alert("Photo cancelled");
        }, {
            destinationType: navigator.camera.DestinationType.FILE_URI
        });
    },

    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        document.getElementById("camera").addEventListener("click", cameraUse, false);
    },

我希望在单击按钮时执行cameraUse 函数。

【问题讨论】:

  • 您的上述错误,将document.getElementById("camera").addEventListener("click", cameraUse, false); 更改为document.getElementById("camera").addEventListener("click", app.cameraUse, false); 您需要在cameraUse 之前添加app. 参见:stackoverflow.com/questions/33778334/… - Javascript 不是Java。

标签: javascript ios cordova camera phonegap-build


【解决方案1】:

您是否下载了科尔多瓦相机plugin,如果没有下载并尝试您的代码

使用
适用于科尔多瓦 5.0+ 版

科尔多瓦插件添加科尔多瓦插件相机

对于旧版本

cordova 插件添加 org.apache.cordova.camera

【讨论】:

【解决方案2】:

将我的 javascript 更改为:

onDeviceReady: function() {
    app.receivedEvent('deviceready');
    document.getElementById("camera").addEventListener("click", function() {
        navigator.camera.getPicture(function(imagePath){
            document.getElementById("photoImg").setAttribute("src", imagePath);
        }, function(){
            alert("Photo cancelled");
        }, {
            destinationType: navigator.camera.DestinationType.FILE_URI
        });
    }, false);
}

不同之处在于我将负责打开摄像头的代码直接移到了addEventListener 调用中,而不是将其放在app 变量中的自己的函数中。

【讨论】:

  • 如果您编辑您的答案并添加有关此更改如何解决您的问题的说明,这将对将来查看此问题的其他人有所帮助。还记得将其标记为已接受的答案。
  • 感谢您的编辑。您可以将自己的答案标记为已接受,以供将来参考,并upvote 任何对您有帮助的答案。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 2023-03-15
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多