簡體   English   中英

從JS運行jquery函數

[英]Running a jquery function from JS

很抱歉這個菜鳥問題,但是今天對我來說沒什么用。

我正在創建一個Phonegap應用程序,並將PushWoosh API集成到我的應用程序中。 在收到推送通知時,我想再次運行以前的功能,因此數據將被更新。

Pushwoosh具有如下的JS功能:

document.addEventListener('push-notification',
    function(event) {
        var title = event.notification.title;
        var userData = event.notification.userdata;
        var notification = event.notification;

        if (typeof(userData) != "undefined") {
            console.warn('user data: ' + JSON.stringify(userData));
        }

        var object = JSON.parse(notification.u);

        window.runPushFunctions(object.active, object.open); //Runs a jQuery function I have created..

    }
);

現在window.runPushFunctions看起來像這樣:

$(document).ready(function() {
    window.runPushFunctions = function(active, open) {

        if (active != null || active != undefined) {
            $('.hubs-page').removeClass('hubs-active').hide().eq(active).show().addClass('hubs-active');
        }

        if (open == 2) {
            $('html').addClass('hubs-opening');
        }

        //Trying to run functions from jQuery file that will get data from database and so on..
        received();
        sent();
        checkFriends();

    };
});

但我不能因為某些原因無法運行received()sent() checkFriends()

這些功能在自己的文件中設置如下:

(function($) {

    'use strict';
    function checkFriends () {
      $.getJSON('url',function(data){
          $.each(data,function(index,value){
             //Do something with value
          });
      });
 }

我按以下順序包括文件:

file.js -> received(); sent();
file.js -> checkFriends();
file.js -> pushnotifications

任何幫助將不勝感激

正如這里的另一個答案所說,您正在對方法定義進行范圍界定,以使在包含方法之外的任何地方都無法訪問它們。

(function($) {

這是一個方法定義。 在其中非全局聲明的任何變量或函數都無法在其外部訪問。 因此,您需要在其他地方定義這些功能或將其全局設置,以使其可訪問。

如果要在其他地方定義它們,則可以簡單地將函數定義移到同一文件的頂部,而不是(function($) {})()范圍。

如果改為使用全局定義,則需要稍微更改方法的定義行:

function foo() { }

你需要

window.foo = function() { }

這會將匿名聲明的函數分配給可全局訪問的window范圍內的對象。 然后您可以使用

window.foo();

或簡單地

foo();

因為它在window范圍內。

我不確定我是否理解您的問題,但是在我看來,就像您在函數作用域內定義函數checkFriends一樣。 如果需要訪問該函數定義,則需要在可以從全局范圍引用的對象上聲明它。 顯然,最簡單的方法是將其連接到窗口,盡管有很多理由不這樣做。

window.checkFriends = function(){//code that does stuff};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM