简体   繁体   English

jQuery选项取消选择事件?

[英]jQuery Option De-Select Event?

I would like to detect the event where an option is de-selected from a select element. 我想检测从选择元素中取消选择选项的事件。 So for instance, if my HTML is: 因此,例如,如果我的HTML是:

<select id="select_box">
    <option value="1">Hot</option>
    <option value="2">Cold</option>
    <option value="3">Just Right</option>
</select>

And the second option is selected ( value="2" ), and then the user de-selects it by clicking on another option (such as value="3" ) or clicking the same option again, how do I detect that event using jQuery? 然后选择第二个选项( value="2" ),然后用户通过单击另一个选项(例如value="3" )或再次单击相同的选项来取消选择它,如何使用jQuery的? My goal is to fire off a function when it happens. 我的目标是在功能发生时将其关闭。

I tried the following: 我尝试了以下方法:

$("#select_box option:selected").change(function() {
    console.log($(this).val());
});

But it didn't work. 但这没有用。

The change event should go on the select element itself: change事件应在select元素本身上进行:

$("#select_box").change(function() {
    console.log($(this).val());
});

This event fires when the value of the select is changed and will match the behaviour you require. 当select的值更改并且与您要求的行为匹配时,将触发此事件。


I want the value of the option that was de-selected. 我想要取消选择的选项的值。

In that case you would need to store the previous value when it's selected, something like this: 在这种情况下,您需要在选择之前的值时将其存储,如下所示:

$("#select_box").change(function() {
    var $select = $(this),
        currentValue = $select.val(),
        oldValue = $select.data('previous-value');

    // do stuff...

    $select.data('previous-value', currentValue);
});

Well, this is how I would handle this with with a change Event listener. 好吧,这就是我如何使用change事件侦听器处理此问题的方法。

$("#select_box").on('change', function(e){
    var $t = $(this), data = $t.data('last') || {optText:'none', val:'none'};
    $t.next().text('last was ['+data.optText+'] and its value is "'+data.val+'"').end()
      .data('last', {optText:$t.children('[value="'+$t.val()+'"]').text(), val:$t.val()});
});

Fiddle HERE 小提琴这里

当使用one()事件绑定方法选择选项时,我将启用元素

change event will fired only when value is changed which is required by you 仅当您需要更改值时,才会触发change事件

        $("#select_box").change(function() {
            console.log(this.value);
        });

You can do it manually some thing like below code i given, 您可以手动执行某些操作,例如我给出的以下代码,

var xSelectedOption = 0;

$("#select_box").change(function() {

    if(xSelectedOption != $(this).val())
    {
      xSelectedOption = $(this).val();

      console.log("Option was changed!");
    }  

});

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

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