js代码,如何点击同类型中的一个标签,输出第几个标签
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Document</title></head...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script type="text/javascript">
function init(){
var pAry=document.getElementsByTagName("p");
for (var i = 0; i < pAry.length; i++) {
pAry[i].onclick=function(){
alert(i+1);
}
}
}
</script>
<body onload="init()">
<p>段落1</p>
<p>段落2</p>
<p>段落3</p>
</body>
</html> 展开
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script type="text/javascript">
function init(){
var pAry=document.getElementsByTagName("p");
for (var i = 0; i < pAry.length; i++) {
pAry[i].onclick=function(){
alert(i+1);
}
}
}
</script>
<body onload="init()">
<p>段落1</p>
<p>段落2</p>
<p>段落3</p>
</body>
</html> 展开
1个回答
展开全部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gbk">
<title>Document</title>
</head>
<script type="text/javascript">
window.onload=function(){
var but = document.getElementsByTagName("p");//p
for(var i=0;i<but.length;i++)
{
but[i].index=i;
but[i].onclick=function(x){
return function(){
alert(x);
}
}(i)
}
}
</script>
<body>
<p>段落1</p>
<p>段落2</p>
<p>段落3</p>
</body>
</html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |