jQuery - 从元素内部选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5808606/
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-26 19:50:32  来源:igfitidea点击:

jQuery - selecting elements from inside a element

jqueryjquery-selectorsparent-child

提问by Alex

let's say I have a markup like this:

假设我有一个这样的标记:

<div id="foo">
  ...
  <span id="moo">
    ...
  </span>
  ...
</div>

and I want to select #moo.

我想选择#moo。

why $('#foo').find('span')works, but $('span', $('#foo'));doesn't ?

为什么$('#foo').find('span')有效,但$('span', $('#foo'));没有?

回答by Jishnu A P

You can use any one these [starting from the fastest]

你可以使用任何一个[从最快的开始]

$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")

Take a look

看一看

回答by Pranay Rana

Actually, $('#id', this); would select #id at any descendant level, not just the immediate child. Try this instead:

实际上, $('#id', this); 将在任何后代级别选择#id,而不仅仅是直接的孩子。试试这个:

$(this).children('#id');

or

或者

$("#foo > #moo")

or

或者

$("#foo > span")

回答by hunter

Why not just use:

为什么不使用:

$("#foo span")

or

或者

$("#foo > span")


$('span', $('#foo'));works fine on my machine ;)

$('span', $('#foo'));在我的机器上工作正常;)

回答by Sai Kalyan Kumar Akshinthala

You can use findoption to select an element inside another. For example, to find an element with id txtNamein a particular div, you can use like

您可以使用findoption 来选择另一个内部的元素。例如,要在特定 div 中查找 id 为txtName的元素,您可以使用 like

var name = $('#div1').find('#txtName').val();

回答by Cody

Have a look here -- to query a sub-element of an element:

看看这里 -查询元素的子元素

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

回答by Mohd Abdul Mujib

....but $('span', $('#foo')); doesn't work?

....但是 $('span', $('#foo')); 不起作用?

This method is called as providing selector context.

这个方法被称为提供选择器上下文

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

在这里,您为 jQuery 选择器提供了第二个参数。它可以是任何 css 对象字符串,就像您将传递给直接选择或 jQuery 元素一样。

eg.

例如。

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

上面的行将选择具有名为 的类的容器中的所有跨度cont1

DEMO

演示

回答by Naftali aka Neal

both seem to be working.

两者似乎都在工作。

see fiddle: http://jsfiddle.net/maniator/PSxkS/

见小提琴:http: //jsfiddle.net/maniator/PSxkS/