我处于需要使用 .wrap 和 :first-child 的情况。
这就是我正在做的事情:
<script>$("a").wrap("<div class='category-wrapper'></div>");</script>
<script>$("div.category-wrapper:first-child").addClass("first");</script>
这应该在链接外部呈现一个 div.category-wrapper,然后向每个第一个 div.category-wrapper 添加一个“第一个”类。
输出为:
<div class="category-wrapper"><a href="#">Test</a></div>
哪个好啊!但是,我无法让“第一个 child ”工作(它不会添加“第一个”类(class))。如果我在其他地方使用它,它会起作用,所以我确信它与前一个元素的动态渲染有关。
示例输出为:
<div class="category-wrapper"><a href="#">Test #1</a></div>
<div class="category-wrapper"><a href="#">Test #2</a></div>
<div class="category-wrapper"><a href="#">Test #3</a></div>
<div class="category-wrapper"><a href="#">Test #4</a></div>
期望的输出:
<div class="category-wrapper first"><a href="#">Test #1</a></div>
<div class="category-wrapper"><a href="#">Test #2</a></div>
<div class="category-wrapper"><a href="#">Test #3</a></div>
<div class="category-wrapper"><a href="#">Test #4</a></div>
但是,我无法让它发挥作用。
最佳答案
first-child 取决于您尝试选择的元素的上下文:"Description: Selects all elements that are the first child of their parent." 。
看看这个:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>First Child Exp</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<style type="text/css">
.first { background-color: red; }
</style>
</head>
<body>
<h1>First Child Exp</h1>
<div>
<div class="category-wrapper"><a href="#">Test</a></div>
</div>
<script type="text/javascript">
$("div.category-wrapper:first-child").addClass("first");
</script>
</body>
</html>
如果删除没有类的 div,则 div class="category-wrapper"将是其父级的第二个子级,因为 h1 将是 body 的第一个子级。如果您随后删除 h1,div class="category-wrapper"将再次成为 body 的第一个子级。
因此,父元素必须包围所有 div class="category-wrapper"元素。
关于jquery - 第一个 child 没有选择预期的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3063437/