Javascript 如何限制jquery搜索范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10543897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:47:31  来源:igfitidea点击:

how to limit the jquery search scope

javascriptjquery

提问by Buzz

It looks like JQuerydoes the search in the current documentwhen using a selector.

使用选择器时,它看起来像JQuery在当前搜索document

How to search for an element only inside a divelement?

如何仅在div元素内部搜索元素?

回答by meagar

jQuery selectors work very much like CSS selectors, which you may be more familiar with.

jQuery 选择器的工作方式与 CSS 选择器非常相似,您可能更熟悉它。

First, select the div, and then descend from that:

首先,选择 div,然后从它下降:

$('#my-div').find('some-selector').

or build your selector to match children of the element in question:

或构建您的选择器以匹配相关元素的子元素:

$('#my-div some-selector')

回答by Gone Coding

Old question, but everyone seems to have missed the scopedjQuery selector (using the scope you desired, i.e. your div selector, as the second parameter)

老问题,但每个人似乎都错过了作用域jQuery 选择器(使用您想要的作用域,即您的 div 选择器,作为第二个参数)

e.g. use

例如使用

var $matches = $('.adiv', '#mydiv');

This is a shorter equivalent of:

这是一个较短的等价物:

var $matches = $('#mydiv').find('.adiv');

回答by epascarello

var elems = jQuery(".foo", jQuery("#divYourWantToLimitTo") );  //BAD
//or
var elems = jQuery("#divYourWantToLimitTo .foo");  //Better
//or
var elems = jQuery("#divYourWantToLimitTo").find(".foo");  //BEST

回答by u283863

jQuery provides several ways to search for specific elements:

jQuery 提供了几种搜索特定元素的方法:

$("#your_div").find(".your_things");        //Find everything inside
  //-or-
$("#your_div").filter(".your_things");      //Find only the top level
  //-or-
$("#your_div .your_things");                //Easiest

回答by Chibuzo

$('div-selector').find('the selector-you-are-looking-for');

回答by Danilo Valente

var elements = $('div ' + yourSearch);