【问题标题】:Accessing functions from an external .js file从外部 .js 文件访问函数
【发布时间】:2024-01-18 08:54:01
【问题描述】:

这是我的 HTML 中的外部 .js 文件。

HTML:li id="getPhoto"

访问此功能的最佳方式是什么。无法让它工作。

$(document).ready(function() {

  $('#getPhoto').click(function() {
      function getPhoto(source) {
         // Retrieve image file location from specified source
            navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
            destinationType: destinationType.FILE_URI,
            sourceType: source });
       }
   });
});

【问题讨论】:

    标签: jquery cordova mobile camera


    【解决方案1】:

    这里没有发生任何事情。当您单击#getPhoto 时,您只是在声明getPhoto() 函数,而不是调用它。这就是你调用函数的方式。

    $('#getPhoto').click(function() {
       getPhoto(someVar);
    });
    
    function getPhoto(source) {
        // Retrieve image file location from specified source
        navigator.camera.getPicture(onPhotoURISuccess, onFail, { 
           quality: 50, 
           destinationType: destinationType.FILE_URI,
           sourceType: source 
        });
    }
    

    这应该会让你走上正确的道路。但看起来你可能有点过头了。

    【讨论】:

    • 感谢您的评论,我有点想这个,但不确定。打算试试这个。
    【解决方案2】:

    确实,您只是在单击时声明该功能。如果你删除几行,你可以使用类似的东西:

    $(document).ready(function() {
     $('#getPhoto').click(function() {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
      destinationType: destinationType.FILE_URI,
      sourceType: source });
     });
    });
    

    您不会将源变量传入,因此您需要找到其他方法将其放入函数中。

    【讨论】:

    • 感谢您的评论,我得试试这个。