<html>
<body>
<table>
<tr>
<td id="a">1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
<body>
<script src='http://172.29.5.201/assets/js/core/jquery.min.js'></script>
<script>
alert($("#a").index());</script>
</html>
<html>
<body>
<table>
<tr>
<td id="a">1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
<body>
<script src='http://172.29.5.201/assets/js/core/jquery.min.js'></script>
<script>
alert($("#a").index());</script>
</html>
function getIndexFromDomOrSelector(domOrSelector){
let dom;
// 检查是dom还是Selector
if(domOrSelector instanceof HTMLElement || domOrSelector instanceof Element){
dom = domOrSelector;
}else if(typeof domOrSelector === "string"){
dom = document.querySelector(domOrSelector);
if(!dom) throw new Error("selector无效,找不到dom")
}else{
throw new Error("参数不合法");
}
// 获取所有的兄弟节点
const brothers = Array.from(dom.parentNode.children);
return brothers.indexOf(dom);
}
// 方式1
getIndexFromDomOrSelector("#a")
// 方式2
const td = document.getElementById("a");
getIndexFromDomOrSelector(td)
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读