Getting an empty JQuery object

前端 未结 4 561
北海茫月
北海茫月 2020-11-30 04:20

In the following code I set up a change handler on a select box to show and hide some follow up questions based on the value of the selection.

Further, for some valu

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 04:49

    My advice is don't do it that way. There are a lot easier ways of doing this. Consider:

    
    
    
    ...
    ...
    ...
    $(function() { $("#select").change(function() { var val = $(this).val(); $("div." + val").show(); $("div:not(." + val + ")").hide(); }); });

    Much easier. Basically give classes to indicate what to show and hide and then there is no tracking required. An alternative is:

    $(function() {
      $("#select").change(function() {
        var val = $(this).val();
        $("div").each(function() {
          if ($(this).hasClass(val)) {
            $(this).show();
          } else {
            $(this).hide();
          }
        });
      });
    });
    

提交回复
热议问题