How do I store multiple jQuery selectors in a javascript variable?

后端 未结 5 1475
野性不改
野性不改 2021-01-25 12:54

Obviously it\'s a good idea to store jQuery selectors in variables if they are used more than once (not a good idea if used only once).

My question is, how do y

5条回答
  •  爱一瞬间的悲伤
    2021-01-25 13:40

    The problem is not the selector string, the problem is the query of the DOM element. "Problem" means, it's expensive. That is why you should only query an element once and store a reference to it.

    var object1 = $('#object1'),
        object2 = $('#object2');
    
    object1.some_method();
    

    update

    In reference to your comment:

    jQuery offers the .add()help method which allows to concat jQuery objects:

    object1.add(object2).method();
    

提交回复
热议问题