How to use JavaScript variables in jQuery selectors?

前端 未结 6 1689
天涯浪人
天涯浪人 2020-11-21 22:38

How do I use JavaScript variables as a parameter in a jQuery selector?



        
6条回答
  •  忘掉有多难
    2020-11-21 23:29

    1. ES6 String Template

      Here is a simple way if you don't need IE/EDGE support

      $(`input[id=${x}]`).hide();
      

      or

      $(`input[id=${$(this).attr("name")}]`).hide();
      

      This is a es6 feature called template string

          (function($) {
              $("input[type=button]").click(function() {
                  var x = $(this).attr("name");
                  $(`input[id=${x}]`).toggle(); //use hide instead of toggle
              });
          })(jQuery);
          
          
          
          
          
      
       


    1. String Concatenation

      If you need IE/EDGE support use

      $("#" + $(this).attr("name")).hide();
      

          (function($) {
              $("input[type=button]").click(function() {
                  $("#" + $(this).attr("name")).toggle(); //use hide instead of toggle
              });
          })(jQuery);
          
          
          
          
          
      
       


    1. Selector in DOM as data attribute

      This is my preferred way as it makes you code really DRY

      // HTML
      
      
      
      //JS
      $($(this).data("input-sel")).hide();
      

          (function($) {
              $(".js-hide-onclick").click(function() {
                  $($(this).data("input-sel")).toggle(); //use hide instead of toggle
              });
          })(jQuery);
          
          
          
          
          
      
       

提交回复
热议问题