簡體   English   中英

在jQuery對話框函數中動態調用JavaScript函數

[英]Call a javascript function dynamically in jquery dialog function

當要按“是”按鈕時,我想在jQuery對話框中調用函數作為參數。 我正在使用以下代碼,但這不起作用。

function showYesNoAlertMsg(divId,optFunction){
 //window[optFunction].apply(null, Array.prototype.slice.call(arguments, 2));
$('#'+divId).dialog('open');
$('#'+divId).dialog({
            autoOpen: true,
            width: 400,
            height: 175,
            modal: true,
            resizable: false,
            buttons: {
                "Yes": function() {
                 window[optFunction].apply(null, 
                                     Array.prototype.slice.call(arguments, 2));
                       $(this).dialog("close");
                },
                "No": function() {
                       $(this).dialog("close");
                }
            }
              });   
             }

       function newfunc(a,b){
            alert(a+'--'+b);
          }


       <input type="button" name="alert" id="alert" 
            onclick="showYesNoAlertMsg('boxDivId','newfunc','aaaaa','bbbbb');"/>

     <div id="boxDivId">
         hello
      </div>

當我單擊名為“ alert”的按鈕時,將調用函數showYesNoAlertMsg ,它會完美顯示id為“ boxDivId”的對話框,但我想在yes按鈕上調用名為“ newFunc”的函數。 我將此函數作為參數傳遞,但在dialog屬性中不起作用。 如果我取消注釋showYesNoAlertMsg的第一條注釋行,則該行可以正常工作,並且可以完美地調用函數“ newFunc”。 但是同一行在“是”按鈕中不起作用。 請告訴我。

謝謝

在類似情況下,我使用了這種方法:

 function showYesNoAlertMsg(divId, optFunction, optFunctionParams) {
      if (!$.isArray(optFunctionParams)) {
           optFunctionParams = Array.prototype.slice.call(arguments, 2);
      }

      $('#' + divId).dialog({
           autoOpen: true,
           width: 400,
           height: 175,
           modal: true,
           resizable: false,
           buttons: {
                "Yes": function () {
                     if (optFunction && typeof optFunction == "function") {
                          optFunction.apply(window, optFunctionParams || []);
                     }
                     $(this).dialog("close");
                },
                "No": function () {
                     $(this).dialog("close");
                }
           }
      });
 }

 function newfunc(a, b) {
      alert(a + '--' + b);
 }

 <input type="button" name="alert" id="alert" value="Click Me"
      onclick="showYesNoAlertMsg('boxDivId', newfunc, ['aaaaa','bbbbb']);" />

如果要使用arguments ,則需要將其值在showYesNoAlertMsg上下文中緩存到某個變量中,如“ Yes按鈕的click事件處理程序中一樣,它已經是該處理程序函數的參數

暫無
暫無

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

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