2017-03-17 19 views
0

在VBA中,您可以通過創建Sub並在代碼中調用它來定義可重用的塊代碼。我明白你不能用同樣的技術在JavaScript中做到這一點,但顯然必須有辦法做到這一點。我明白你可以使用函數,但我真的不能使它的頭或尾。我想在我的程序中多次調用下面的代碼,這怎麼能在JavaScript中實現?JavaScript中的子例程

$("select[title='Mon']").prop("disabled", true); 
$("input[title='M1Sent']").prop("disabled", true); 
$("input[title='HotelCheckIn']").prop("disabled", true); 
$("input[title='HotelCheckOut']").prop("disabled", true); 
$("textarea[title='Diet']").prop("disabled", true); 

感謝

+0

你有一個單一的JavaScript文件?請注意,在JavaScript中,您沒有名稱空間,用途等。 –

+0

函數就是你想要的 – j08691

+2

將你的代碼包裝在一個函數中:'function myFunc(){/ * code * /}',並將其稱爲: 'myFunc();' –

回答

1

首先,創建一個功能:

function myFunction() { 
    //what you want executed goes here 
} 

那你就把你想在這個函數做了什麼:

function myFunction() { 
    $("select[title='Mon']").prop("disabled", true); 
    $("input[title='M1Sent']").prop("disabled", true); 
    $("input[title='HotelCheckIn']").prop("disabled", true); 
    $("input[title='HotelCheckOut']").prop("disabled", true); 
    $("textarea[title='Diet']").prop("disabled", true); 
} 

,並呼籲它,你只需要輸入myFunction();,你可以做無論你希望多少次。

或者,如果你想重複一遍又一遍,你可以彈出myFunctionsetInterval(myFunction, milliseconds)或將其綁定到一個HTML元素的一些事件,例如<input type="submit" onsubmit="myFunction();"> ... </input>

+0

非常感謝!我會給它一個鏡頭,這似乎正是我所期待的。乾杯 –

0

首先定義函數:

function doThings() { 
    $("select[title='Mon']").prop("disabled", true); 
    $("input[title='M1Sent']").prop("disabled", true); 
    $("input[title='HotelCheckIn']").prop("disabled", true); 
    $("input[title='HotelCheckOut']").prop("disabled", true); 
    $("textarea[title='Diet']").prop("disabled", true); 
} 

您現在可以反覆調用這個函數是這樣的:

doThings(); 
0

把你的片段中單獨的JavaScript文件,如果你想
2-之前,請確保您要在使用它的任何其他子代碼加載它。
3- jQuery的是這裏的依賴性,因此你的腳本需要包括jQuery的後

var usable = function() { 
     var myFunction = function() { 
      $("select[title='Mon']").prop("disabled", true); 
      $("input[title='M1Sent']").prop("disabled", true); 
      $("input[title='HotelCheckIn']").prop("disabled", true); 
      $("input[title='HotelCheckOut']").prop("disabled", true); 
      $("textarea[title='Diet']").prop("disabled", true); 
     } 
     return { 
      myFunction: myFunction 
     }; 
    }(); 

你可以添加任何可重複使用的功能,然後調用它像這樣:

usable.myFunction() 

,只是包括它像在你的HTML正常的JavaScript文件。

+1

從技術上講,一個固定的解決方案,但你可能會希望在單獨的步驟中引入函數範例和模塊模式,因爲OP可能不熟悉這兩者。 –