简体   繁体   English

从选项对象中选择选项时,jQuery 执行函数

[英]jQuery execute function when option is selected from option object

I am dynamically creating the options for a select element using jQuery.我正在使用 jQuery 动态创建选择元素的选项。 Is it possible in jQuery to setup a function to be executed when that option is selected?是否可以在 jQuery 中设置要在选择该选项时执行的函数?

I know I can detect the change of the entire select element, but is it possible to specify this on a per-option basis?我知道我可以检测到整个 select 元素的变化,但是是否可以在每个选项的基础上指定它? Maybe something like this:也许是这样的:

$('<option />').onselect(function(){

 // do something

});

Edit: If it's not possible to specify a function that get's executed when a specific option is selected, is it possible to bind a function to an element in jQuery?编辑:如果无法指定在选择特定选项时执行的函数,是否可以将函数绑定到 jQuery 中的元素? It would make my logic cleaner by allowing me to just simply execute that function assigned to the option in the .change for the select.通过允许我简单地执行分配给选择的 .change 中的选项的函数,这将使我的逻辑更清晰。

You can delegate a change event to the document and attach an event handler to the select element.您可以将change事件委托给文档并将事件处理程序附加到select元素。 This allows for runtime manipulation:这允许运行时操作:

$(document).on('change', 'select', function() {
    console.log($(this).val()); // the selected options’s value

    // if you want to do stuff based on the OPTION element:
    var opt = $(this).find('option:selected')[0];
    // use switch or if/else etc.
});

Or if you insist on creating functions for each OPTION, you can do:或者,如果您坚持为每个 OPTION 创建函数,您可以这样做:

$('<option>').data('onselect', function() {
    alert('I’m selected');
});

$(document).on('change', 'select', function(e) {
    var selected = $(this).find('option:selected'),
        handler = selected.data('onselect');
    if ( typeof handler == 'function' ) {
        handler.call(selected, e);
    }
});

You can use onchange handler to the select:您可以对选择使用 onchange 处理程序:

<select name='numbers' id='numbers'>
  <option value='1' selected='selected'>One</option>
  <option value='2'>two</option>
  <option value='3'>three</option>
  <option value='4'>four</option>
</select>

<script>
  $('#numbers').change(function () { 
    if ($(this).val() === '1'){
      function1();
    }
    if ($(this).val() === '2'){
      function2();
    }
});
</script>

Best Regards最好的祝福

What you can try is binding the change() event on the select element itself.您可以尝试在select元素本身上绑定change()事件。 From there, assuming you have a valid function for each option, you can call an individual option's callback:从那里,假设您对每个选项都有一个有效的函数,您可以调用单个选项的回调:

$('select').change(function() {
  var type = $(this).val();
  switch(type) {
  }

  // Alternatively, you can try this as well:
  $(this).find('option:selected').each(function() {
  });
});

If you are saying you want to assign individual functions to each option element you can do something like this:如果您说要为每个选项元素分配单独的功能,您可以执行以下操作:

var options = [{"value" : "1",
                "display" : "One",
                "fn" : function() { console.log("One clicked"); }
               },
               {"value" : "2",
                "display" : "Two",
                "fn" : function() { console.log($(this).val() +  " clicked"); }
               }];

var $select = $("select").on("change", function() {
    var opt = this.options[this.selectedIndex];
    $(opt).data("fn").call(opt);
});

$.each(options, function(i, val) {
    $select.append(
        $("<option/>").attr("value", val.value)
                      .text(val.display)
                      .data("fn", val.fn)
    );
});

​Demo: http://jsfiddle.net/6H6cu/演示: http : //jsfiddle.net/6H6cu/

This actually attaches functions to each option using jQuery's .data() method, and then on click/keyup on the select element it calls the appropriate options function (setting this to the option).这实际上使用jQuery的附加功能,每个选项.data()方法,并选择元素然后点击/ KEYUP它调用相应的功能选项(设置this为选项)。

In my opinion that is way overkill, but it seems to be what you are asking.在我看来,这有点矫枉过正,但这似乎正是您要问的。

I guess a simpler version would be something like:我想一个更简单的版本是这样的:

var optionFunctions = {
   "1" : function() { ... },
   "2" : function() { ... },
   ...
};

// code to create the options omitted

$("select").on("change", function() {
    var fn = optionFunctions[$(this).val()];
    if (fn)
       fn.call(this.options[this.selectedIndex]);
});

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

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