繁体   English   中英

如何在函数IN jquery之外获取变量值

[英]How to get variable value outside a function IN jquery

我有一个变量我在一个函数内部给它赋值现在我想在这个变量之外得到这个值但我得到未定义,下面是我的代码。 我在我的页面上有select2,我希望根据用户的选择填充一些数据,我允许用户选择一个单选按钮,我得到单选按钮的值,以确定在选择菜单中显示哪些数据。 现在我的编码后我可以在onclick事件函数中提醒var size_data但是无法将这个值传递给我需要它的select2,对此的任何帮助将不胜感激

注意 var size_data是一个全局变量,包含不同大小的变量也是全局变量

看看我在FIDDLE上的DEMO

var uk_size = [{ id: '8', text: '8' },
                { id: '10', text: '10' }, 
                { id: '12', text: '12' },
            ];
var us_size = [{ id: '4', text: '4' },
                { id: '6', text: '6' }, 
                { id: '8', text: '8' },
                { id: '10', text: '10' }, 
            ];
var eu_size = [{ id: '34', text: '34' },
                { id: '36', text: '36' }, 
                { id: '38', text: '38' },
            ];
var ng_size = [{ id: 'XS', text: 'XS' },
                { id: 'S', text: 'S' }, 
                { id: 'M', text: 'M' },
            ];
var size_data = ng_size; //default value;
//alert(ng_size);
   $("#size-style input:radio").on('click',function() {
              //alert(ng_size);

                  var size_style ="";
                size_style = $(this).val();
                if (size_style === "ng-size"){
                      size_data = ng_size;  
                }else if(size_style === "uk-size"){
                      size_data = uk_size; 
                }else if(size_style === "us-size"){
                      size_data = us_size;
                }else{
                    size_data = eu_size;
                }
                alert(size_data);//can alert jquery object here
    });



$('select.size-select').select2({
        name: 'size',
        value: 'S',
        data: size_data,
        tags: "true",
        placeholder: "Select size",
        allowClear: true
    });

您可以先使用默认值初始化select2 ,然后在单选按钮单击事件中,您可以修改其数据,如下所示:

https://fiddle.jshell.net/nnaL44ur/4/

$("#size-style input:radio").on('click', function() {
  //alert(ng_size);

  var size_style = "";
  size_style = $(this).val();
  if (size_style === "ng-size") {
    size_data = ng_size;
  } else if (size_style === "uk-size") {
    size_data = uk_size;
  } else if (size_style === "us-size") {
    size_data = us_size;
  } else {
    size_data = eu_size;
  }
  alert(size_data); //can alert jquery object here

  var $select = $('select.size-select'); //grabbing the select element

  //fetching the previously set options at the first time initialization of select2 widget
  var options = $select.data('select2').options.options;

  $select.html(''); //clearing the previous dropdown options
  // add new items to the options
  options.data = size_data;
  $select.select2(options); //updating the select2 widget with newer set of option data

});

希望它会对你有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM