[英]How to make this unnamed function to general function that we can just call?
這是腳本:
$(function(){
// Set up the number formatting.
$('#price').on('change',function(){
console.log();
var val = $('#price').val();
});
$('#price').change(function(){
console.log();
});
$('#price').number( true, 5 );
});
可以在需要時調用通用函數嗎?
當然:
function setupPriceChange() {
// Set up the number formatting.
$('#price').on('change',function(){
console.log();
var val = $('#price').val();
});
$('#price').change(function(){
console.log();
});
$('#price').number( true, 5 );
}
// from somewhere else in your script:
setupPriceChange();
您可以隨意命名函數。 您可以在MDN上找到有關JS函數的詳細說明。
您需要重構代碼以將函數保存在變量中,並在需要執行這些腳本時調用該變量。 像下面
var generalFunction = function(){ // Or general syntax function generalFunction(){
// Set up the number formatting.
$('#price').on('change',function(){
console.log();
var val = $('#price').val();
});
$('#price').change(function(){
console.log();
});
$('#price').number( true, 5 );
}
$(function(){
generalFunction(); // once on document ready
});
這樣,您只需要執行generalFunction();
每當您想要執行這些腳本時。
$(function(){}); 是$(document).ready(function(){}); 將其更改為命名函數,可以將其替換為以下片段
$(document).ready(Init); function Init(){ alert("hello"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
並且您的代碼可以按以下代碼段進行更改
$(function(){ // Set up the number formatting. $('#price').on('change',priceChange); }); function priceChange(){ console.log(); var val = $('#price').val(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.