不要又给我长长的代码,怎么用也不说,说的太复杂或含糊不清。
纯JavaScript。
我写的(失败):
JavaScript:
var colorr=document.getElementsByTagName("cyif_head").getAttribute("cyif-color");
alert(colorr);
html:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>标题</title>
<script src="cyif.js"></script>
</head>
<body>
内容
<cyif_head cyif-color="#DC143C"></cyif_head>
</body>
</html>
getElementsByTagName返回的是包含指定标签名的集合,我们要取的是第一个(数组,集合索引下标都是从0开始),所以加个[0],就能得到结果了
修改如下:
var colorr=document.getElementsByTagName("cyif_head")[0].getAttribute("cyif-color");
alert(colorr);
补充说明:
<cyif_head cyif-color="#DC143C"></cyif_head>
我们想获取指定的标签 cyif_head 有三种方式:
1.getElementsByTagName, 返回指定标签名的所有子元素集合,就是问题里面的方式
2.getElementsByClassName,返回有指定类名的元素集合,跟1一样结果都是集合,取第一个就是加[0]
首先需要给它一个类名,使用class="类名"
<cyif_head class="exampleClass" cyif-color="#DC143C"></cyif_head>
然后js处理的话就是:
var colorr=document.getElementsByClassName("exampleClass")[0].getAttribute("cyif-color");
alert(colorr);
3.getElementById,返回对拥有指定 ID 的第一个对象的引用,这个是唯一的值
首先需要给它一个ID名,使用id="id名"
<cyif_head id="exampleId" cyif-color="#DC143C"></cyif_head>
然后js处理的话就是:
var colorr=document.getElementById("exampleId").getAttribute("cyif-color");
alert(colorr);