2012-01-15 30 views
4

之間共享功能我有jQuery中定義爲這樣一些很好的對話:jQuery的:網頁代碼​​和代碼的document.ready

<script type="text/javascript"> 
$(document).ready(function() { 

    $("#someDialog").dialog({ 
     autoOpen: false, 
     model: true, 
     buttons: { 
      "Do Something": function() { 
       var cleanInput = sanitizeInput(input); 
       // Do something with the clean input 
      }, 
      Cancel: function() { 
       $(this).dialog("close"); 
      } 
     }, 
     close: function() { 
     } 
    }); 

    function sanitizeInput(input) { 
     // Some magic here 
     return input; 
    } 
}); 
</script> 

某處在頁面上,無關的對話,我有一個調用的元素

<a href="#" onclick="doSomething('wendy');">Wendy's stats</a> 

和相關的JavaScript:帶有參數的功能

<script type="text/javascript"> 

function doSomething(input) { 
    var cleanInput = sanitizeInput(input); 
    // Some code here 
} 

</script> 

我想重用該函數的sanitizeInput()函數。但是,從document.ready函數之外,該對話框不起作用。將doSomething()函數放入document.ready函數中同樣會將其分解。那麼我應該在哪裏放置sanitizeInput()函數,以便兩者都可以使用它?

謝謝。

回答

3

您只需將該功能移到ready()回調之外即可。

$(document).ready(function() { 

    $("#someDialog").dialog({ 
     autoOpen: false, 
     model: true, 
     buttons: { 
      "Do Something": function() { 
       var cleanInput = sanitizeInput(input); 
       // Do something with the clean input 
      }, 
      Cancel: function() { 
       $(this).dialog("close"); 
      } 
     }, 
     close: function() { 
     } 
    }); 
}); 

    /*** Make it global ***/ 
function sanitizeInput(input) { 
    // Some magic here 
    return input; 
} 

現在sanitizeInput()是全球可用,而不是侷限在ready()回調的變量範圍。

+0

當的javascript在document.ready函數之外,那麼該函數中的代碼不能使用它。我已將這個簡化爲一個非常簡單的示例,並在Firefox 7中進行了測試,這是我的目標瀏覽器之一。 – dotancohen 2012-01-15 17:21:55

+1

@dotancohen:這是不對的。回調函數內的'ready()'回調之外的任何函數/變量都可用。這就是詞法範圍的工作原理。但是,如果你做了'var sanitizeInput = function(...',那麼你需要確保它在你的'ready()'調用之前* – 2012-01-15 17:24:25

+1

...如果它不工作,那麼你'需要在你的問題中包含非工作代碼 – 2012-01-15 17:25:11

2

此外,我會建議一些小的更改。

<a href="#" onclick="doSomething('wendy');">Wendy's stats</a> 

有:

首先,我將取代這個

<a href="#" data-name="wendy or server var">Wendy's stats</a> 

,然後添加這個到$(document).ready塊的結尾:

$("a[data-name]").click(function (e) { 
    e.preventDefault(); 
    doSomething($(this).data("name")); 
}); 
+0

謝謝,我應該在哪裏看到那本精美的手冊? – dotancohen 2012-01-15 17:28:12

+1

從http://api.jquery.com/category/events/和http://api.jquery.com/data/ – karim79 2012-01-15 17:30:48

+0

開始謝謝Karim!我發現這取決於HTML5,我不確定它可以在所有常見的瀏覽器中運行,但我會稍微嘗試一下。謝謝! – dotancohen 2012-01-15 18:11:01