How to use JavaScript variables in jQuery selectors?

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

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



        
6条回答
  •  野的像风
    2020-11-21 23:29

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

    As you're using an ID, this would perform better

    $(`#${this.name}`).hide();
    

    I highly recommend being more specific with your approach to hiding elements via button clicks. I would opt for using data-attributes instead. For example

    
    
    

    Then, in your JavaScript

    // using event delegation so no need to wrap it in .ready()
    $(document).on('click', 'button[data-target]', function() {
        var $this = $(this),
            target = $($this.data('target')),
            method = $this.data('method') || 'hide';
        target[method]();
    });
    

    Now you can completely control which element you're targeting and what happens to it via the HTML. For example, you could use data-target=".some-class" and data-method="fadeOut" to fade-out a collection of elements.

提交回复
热议问题