代码之家  ›  专栏  ›  技术社区  ›  user3052443

将变量传递到对话框按钮

  •  0
  • user3052443  · 技术社区  · 6 年前

    我在对话框中添加了一个按钮。单击后,它将从对话框中获取结果并将其显示在主页面上。可能有很多元素需要这样做,所以我尝试制作一个可以与所有元素一起工作的函数。但为了做到这一点,我需要将名称传递给该函数,我不知道如何在不使用全局变量的情况下做到这一点。

    例如,下面的代码显示了正在调用的对话框。“which”参数可以是任意数量的东西。在GetResults函数中,无论使用哪个参数,都会获取结果。代码可以正常工作,但我尽量不使用全局变量。这可能吗?

        <script>
        var gwhich = '';
        function ShowTheDialog(which) {
          var dWidth = 200; 
          var dHeight = 350; 
          var name = '';
          var thisurl = '';
          switch (which) {
            //set vars here
          }
          gwhich = which;
    
          $.ajax({
            url:thisurl,
            success: function(data) {
            $("#show-dialog").html(data).dialog({modal:true}).dialog({options: 
              open, 
              title:name, 
              width:dWidth, 
              height:dHeight,
    
              buttons: { 
                 "Save": GetResults,
                 "Cancel": function() {
                    text:'Cancel',
                     $(this).dialog("close");
                 }      
              },
             });
            }
          });
        } 
        function GetResults(){ 
          which = gwhich;
          var selectedItem = $("#retval-selected").text();
          var apply_to = $("#retval-apply-to").text();
          $("#show-selected-"+which).val(selectedItem);
          $("#show-apply-to-"+which).val(apply_to);
          $("#show-dialog").dialog( "close" );
        }
        </script>
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   McBern    6 年前

    您可以将which参数传递给GetResults();

         buttons: { 
                 "Save": function() {
                    GetResults(which);
                 },
                 "Cancel": function() {
                    text:'Cancel',
                     $(this).dialog("close");
                 }      
              },
    
    
       function GetResults(which){ 
          var selectedItem = $("#retval-selected").text();
          var apply_to = $("#retval-apply-to").text();
          $("#show-selected-"+which).val(selectedItem);
          $("#show-apply-to-"+which).val(apply_to);
          $("#show-dialog").dialog( "close" );
        }