您的位置:首页 > Web前端 > HTML

修正IE下document.getElementsByName无法获取DIV标签

2012-05-18 18:59 387 查看
<!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>无标题文档</title>

<style>

div{

    width: 100px;

    height: 100px;

    border:1px solid red;

}

</style>

</head>

<body>

<div name="odiv">div1</div>

<div name="odiv">div2</div>

<div name="odiv">div3</div>

<div name="odiv">div4</div>

<div name="anotherdiv">AnotherDiv</div>

<script type="text/javascript">

<!--

// 可见在IE下通过document.getElementsByName是无法获取DIV标签的,FF可以

alert(document.getElementsByName("odiv").length); // IE:0 FF:4

// 兼容IE FF的ByName方法

var getElementsByName = function(tag, name){

    var returns = document.getElementsByName(name);

    if(returns.length > 0) return returns;

    returns = new Array();

    var e = document.getElementsByTagName(tag);

    for(var i = 0; i < e.length; i++){

        if(e[i].getAttribute("name") == name){

            returns[returns.length] = e[i];

        }

    }

    return returns;

}

alert(getElementsByName("div","odiv").length); // IE:4 FF:4

//-->

</script>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ie div xhtml border function html