作为 Chrome 扩展的一部分,我有一行代码在作为游戏一部分的页面上查找元素并添加一些 html。我所在的页面连续有几个没有类或 ID 的 div,我正试图定位第一个以添加我的 html。有一个包含唯一文本的 h2 元素,所以我将其作为目标,然后尝试使用 parents().eq(x) 来获取我想要的 div。如果我使用 eq(1) 它会获取 h2 的父元素,但是如果我使用 eq(2) 它会跳过第二个 div 向上移动树,而是将目标放在它上面的元素上。
这是我的代码行:
$("h2:contains(New Amsterdam)").parents().eq(1).prepend("<span class=\"HideFJcontainer\" style=\"font-size:18px;\"> <input type=\"checkbox\" Id=\"HideFJtrophy\" title=\"When checked your trophies will be hidden\"> Hide/Show</span>");
我正在使用的部分页面的 HTML 是:
<div class="container extraBottom">
<div id="snackbar"></div>
<div class="col-sm-12 text-center">
<h1>Rogues Gallery</h1>
</div>
<div>
<div>
<h2>New Amsterdam
当我使用 eq(1) 时,它会在 h2 上方的第一个 div 之前添加我的跨度,但是,如果我使用 eq(2),它会将它放在 ID 为 snackbar 的 div 之前。
谁能解释我做错了什么?
谢谢!
*****示例 1 使用 eq(1)*****
<div class="container extraBottom">
<div id="snackbar"></div>
<div id="FJholder"></div>
<div class="col-sm-12 text-center">
<h1>Rogues Gallery</h1>
</div>
<div><span class="HideFJcontainer" style="font-size:18px;"> <input type="checkbox" id="HideFJtrophy" title="When checked your trophies will be hidden" checked="checked"> Hide/Show</span>
<div>
<h2>New Amsterdam</span>
</h2>
*****使用 eq(2) 的示例 2*****
<div class="container extraBottom">
<span class="HideFJcontainer" style="font-size:18px;"> <input type="checkbox" id="HideFJtrophy" title="When checked your trophies will be hidden" checked="checked"> Hide/Show</span>
<div id="snackbar"></div>
<div id="FJholder"></div>
<div class="col-sm-12 text-center">
<h1>Rogues Gallery</h1>
</div>
<div>
<div>
<h2>New Amsterdam</span>
</h2>
如果我使用 eq(1) 它得到 h2 的父...
不,它获取h2
的父级的
parent,因为
eq
以0
开头。 parents
返回一个 jQuery 集,其中第一个条目 (.eq(0)
) 是父母,下一个是祖父母 (.eq(1)
),依此类推。
如果你想将 span 插入到
h2
的父级中,那么 eq(1)
是正确的使用方法。我添加了边框以使发生的事情更清楚:
$("h2:contains(New Amsterdam)").parents().eq(1).prepend("<span class=\"HideFJcontainer\" style=\"font-size:18px;\"> <input type=\"checkbox\" Id=\"HideFJtrophy\" title=\"When checked your trophies will be hidden\"> Hide/Show</span>");
.parent {
border: 1px solid blue;
}
.grandparent {
border: 1px solid green;
}
<div class="container extraBottom">
<div id="snackbar"></div>
<div class="col-sm-12 text-center">
<h1>Rogues Gallery</h1>
</div>
<div class="grandparent">
<div class="parent">
<h2>New Amsterdam</h2>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
它得到
h2
的父级的父级,因为eq
以0开头。