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

使用jquery根据所选单选按钮和选项更改所选选项卡

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

    我想实现以下目标:

    如果从选择列表中选择了德国以外的国家(de),并且当前选择了“打印”选项卡,则应选择“数字”选项卡,应向上滚动页面并显示警告框。

    到目前为止,我的代码仍在工作,但第二个if循环的第二个条件未计算:

    if (this.value! = 'de' && $("input [value = 'print']"). prop ("checked", true)) {
        ..
    }
    

    因此,每次从选择列表中进行选择时,选项卡都会更改为“数字”,页面会向上滚动,尽管只有在选择了“打印”选项卡的情况下才应如此。

    这是我的完整代码:

    // if a country other than germany is elected, set selected tab to digital and scroll to top
    $("select[name='country']").change(function(e){
        $("select[name='country'] option").each(function() {
            if (this.selected) {
                if (this.value != 'de' && $("input[value='print']").prop("checked", true) ) {
                    $("input[value='digital']").prop("checked", true);
                    $("form .alert").css({display: 'block'});
                    var target = $('#top');
                     $('html, body').animate({
                       scrollTop:$(target).offset().top
                     },'slow');
                     e.preventDefault();    
                }                           
            }
        });
    });
    

    下面是包含所述选项卡和选择列表的页面:

    https://www.academyofsports.de/de/anmeldung/fernstudium.html?product=fitness-c-lizenz


    更新的“解决方案”:

    // if a country other than germany is elected, set selected tab to digital and scroll to top
    $("select[name='country']").on("change", function(e) {
        var isDE = this.value == 'de';
        if (!$("input[value='print']").is(":checked")) 
            return;
            $("form .alert").toggle(!isDE);
        if (isDE) 
            return;
        $("input[value='digital']").prop("checked", true);
        $("input[value='print']").prop( "disabled", true );
        $("select[name='country']").on('change', function() {
            if(isDE){
                $("input[value='print']").prop( "disabled", true );
            }
            else{
                $("input[value='print']").prop( "disabled", false );
            }
        });
        var target = $('#top');
        $('html, body').animate({
          scrollTop: $(target).offset().top
        }, 'slow');
    });
    

    这样它现在可以工作了,但是如果进程重复,disable函数将不再工作。为什么?

    该功能现已启用,可以在此处进行测试:

    https://www.academyofsports.de/de/anmeldung/fernstudium.html?产品=健身-C-LIZENZ

    1 回复  |  直到 6 年前
        1
  •  1
  •   mplungjan Gvidas    6 年前

    也许你是这个意思?

    无论如何,它更容易阅读和修改

    $("select[name='country']").on("change", function(e) {
      var isDE = this.value == 'de';
      $("form .alert").toggle(!isDE);
      if (isDE) return;
      if (!$("input[value='print']").is(":checked")) return;
      e.preventDefault(); // Why?
      $("input[value='digital']").prop("checked", true);
      var target = $('#top');
      $('html, body').animate({
        scrollTop: $(target).offset().top
      }, 'slow');
    });
    

    替代方案是

    $('#top')[0].scrollIntoView();