【问题标题】:How to prevent JQUERY change() function triggering when default select option selected选择默认选择选项时如何防止触发 JQUERY change() 函数
【发布时间】:2014-09-02 00:49:51
【问题描述】:

我想防止我的 JQUERY change() 函数在从下拉菜单中选择默认选择选项时触发。但是,如果选择了下拉菜单中的任何其他选项,我希望触发该功能。

在下面的示例中,安道尔是默认选择选项,因此我希望在从下拉列表中选择任何其他国家/地区时触发 change() 函数。

HTML

<select id="customer_country" name="customer_country"
class="validate[required] input_styling target"
style="background: #FFFFFF;">
                <option value="">Please Select a Country</option>
                <option value="Afghanistan">Afghanistan</option>
                <option value="Åland Islands">Åland Islands</option>
                <option value="Albania">Albania</option>
                <option value="Algeria">Algeria</option>
                <option value="American Samoa">American Samoa</option>
                <option value="Andorra" selected>Andorra</option>
...

</select>

JQUERY

$(document).ready(function(){
    // show popup when selecting a country from the drop-down
    $( ".target" ).change(function() {
        var docHeight = $(document).height(); //grab the height of the page
        var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
        $('.overlay-bg').show().css({'height' : docHeight}); //display your popup and set height to the page height
        $('.overlay-content').css({'top': scrollTop+20+'px'}); //set the content 20px from the window top
    });

任何帮助都会很棒。

【问题讨论】:

  • 在 DOM 准备就绪时获取默认选择值,然后将其与更改处理程序中的选择值进行比较 - here's a fiddle

标签: javascript jquery html


【解决方案1】:

将函数包装在 if 语句中,将默认值 ("") 与所选值进行比较

  $( ".target" ).change(function() {
     if($(this).val() != "") {
        var docHeight = $(document).height();
        var scrollTop = $(window).scrollTop(); 
        $('.overlay-bg').show().css({'height' : docHeight}); 
        $('.overlay-content').css({'top': scrollTop+20+'px'});
     }
    });

如果需要帮助澄清,这里是 JSFiddle(我简化了 .change(),但你明白了)。

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 1970-01-01
    • 2017-05-28
    • 2017-12-18
    • 1970-01-01
    • 2019-05-22
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多