我正在使用查询index()方法来获取元素相对于其父元素的索引。
这里有两个代码: 代码1
<div id="check1">
<p>
<span>
<b> Bold Line 1 </b>
<b> This is line2 </b>
</span>
</p>
<p> Should have index 1 </p>
</div>
代码2
<div id="check2">
<p>
<span>
<b> Bold Line 1 </b>
**<p> This is line2 </p>** //replaced <b> with <p>
</span>
</p>
<p> Should have index 1 </p>
</div>
在代码2中,我刚刚用p标签名称替换了第二个粗体名称。
在这两种情况下,问题的答案各不相同。 答案是:
Case1: index comes 1
Case2: index comes 3
请检查一下。 “单击应该有索引 1” http://jsfiddle.net/blunderboy/U73VV/
此外,当我在两张支票上单击“这是第 2 行”时,他们的 parent 会以不同的方式出现。在 check1 中,父级是 span,在 check2 中父级是 div。
请让我知道仅更改 tagName 会产生什么影响。他们相对于 parent 的相对位置仍然相同。
最佳答案
您无法放置<p/>
里面的标签<p/>
标签。您最终会得到以下标记:
<div id="check2">
<p>
<span>
<b> Bold Line 1 </b>
</span>
</p>
<p> This is line2 </p>
<p> Should have index 1 </p>
</div>
您可能想要替换 <b/>
与 <span/>
而不是保留布局。
或者,如果您想要更改 bold
标签的属性,你可以使用CSS。这不需要您搞乱布局。
.bold { text-weight: bold; }
切换bold
类:
<div id="check1">
<p>
<span>
<!-- This is bold -->
<span class="bold"> Bold Line 1 </span>
<!-- This one is not bold -->
<span> This is line2 </span>
</span>
</p>
<p> Should have index 1 </p>
关于Jquery index() 方法获取子节点的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11045482/