Comma separated list of selectors?

前端 未结 4 1005
一向
一向 2020-12-15 17:59

I\'m refactoring some code at the moment and have come across a selector:

jQuery(\"tr\",\"#ctl00_MainContent_MyUserControl\").each(function(i,row) { ... }


        
相关标签:
4条回答
  • 2020-12-15 18:19

    It's exactly the same. It could also have been written:

    $("#ctl00_MainContent_MyUserControl").find("tr").each(function(i,row) { ... }
    

    The syntax for the former can be seen in the jQuery constructor documentation. It's basically "find all elements that matches the first selector, that's a descendant of the second matched by the second".

    0 讨论(0)
  • 2020-12-15 18:22

    Calling the jQuery() method with two arguments (selector and context) is equivalent to jQuery(context).find(selector). Thus:

    jQuery("tr","#ctl00_MainContent_MyUserControl");
    

    is equal to:

    jQuery("#ctl00_MainContent_MyUserControl").find("tr");
    

    which also happens to be the same as:

    jQuery("#ctl00_MainContent_MyUserControl tr");
    

    My personal opinion is that the use of context only makes sense when you can pass an already selected element (jQuery or DOM), not so much when you just pass a selector (String). In that case I simply prefer to mimic the CSS selector: e.g., #ctl00_MainContent_MyUserControl tr.

    0 讨论(0)
  • 2020-12-15 18:30

    This selector selects all tr elements inside an element with id ctl00_MainContent_MyUserControl. It is exactly the same as your second example.

    The second parameter provides a context for the first parameter. There are better use cases for this syntax, for example:

    function(el) {
        $('tr', el).each(...);
    }
    

    Where el is some element on your page. In this case, you can't use the second syntax form.

    0 讨论(0)
  • 2020-12-15 18:42

    The second argument to the jQuery constructor (when the first is a selector) is the context.

    From the API docs

    context A DOM Element, Document, or jQuery to use as context

    See http://api.jquery.com/jQuery/

    0 讨论(0)
提交回复
热议问题