How to use JavaScript variables in jQuery selectors?

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

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



        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:17

    $("input").click(function(){
            var name = $(this).attr("name");
            $('input[name="' + name + '"]').hide();    
        });   
    

    Also works with ID:

    var id = $(this).attr("id");
    $('input[id="' + id + '"]').hide();
    

    when, (sometimes)

    $('input#' + id).hide();
    

    does not work, as it should.

    You can even do both:

    $('input[name="' + name + '"][id="' + id + '"]').hide();
    

提交回复
热议问题