我是一个Javascript初学者。我想获得多个类元素的属性值。我尝试使用ID,但由于ID应该是唯一的,所以它不是很有意思。
我的HTML看起来像这样:
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_1">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_2">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_3">
任何帮助都将不胜感激。
由于
答案 0 :(得分:1)
首先关闭你的锚标签
<a href="#" class="Test" onclick="return myJavascriptFunc(this);" data="FooBar_1">Test1</a>
<a href="#" class="Test" onclick="return myJavascriptFunc(this)" data="FooBar_2">Test2</a>
<a href="#" class="Test" onclick="return myJavascriptFunc(this)" data="FooBar_3">Test3</a>
然后使用这个javascript函数
function myJavascriptFunc(item)
{
alert(item.getAttribute("data"));
return false
}
让我知道它是否有效
答案 1 :(得分:0)
尝试使用:
function test(){
var x = document.getElementsByClassName("myClass");
var i;
for (i = 0; i < x.length; i++) {
var val = x[i].innerHTML; //innerHTML returns the written text inside the element tag
alert(val);
alert(x[i].getAttribute("data")); //this will give you the data attribute
}
}
您可以通过用该属性替换innerHTML来获取您喜欢的任何其他属性
答案 2 :(得分:0)
我一如既往地太迟了,但我会使用HTML 5数据集属性:
<!DOCTYPE html>
<html>
<head>
<script>
function doSomething(classname,func,datakey)
{
var hrefs = document.getElementsByClassName(classname), // get all elements with the class
i = 0; // initialize the loop
for(;i < hrefs.length; i++) // iterate through all elements
{
func(hrefs[i].dataset[datakey]); // execute the passed function with the content of the dataset as first argument
}
}
function alertval(value) // example function to do something with it
{
alert(value);
}
window.onload = function ()
{
doSomething("Test",alertval,"something"); // just test it
}
</script>
</head>
<body>
<a href="#" class="Test" data-something="FooBar_1">Test1</a>
<a href="#" class="Test" data-something="FooBar_2">Test2</a>
<a href="#" class="Test" data-something="FooBar_3">Test3</a>
</body>
</html>
答案 3 :(得分:0)
您可能想知道为什么不能使用data
中的this
关键字来获取myJavascriptFunc()
属性。这是因为您使用内联事件注册,然后this
关键字引用window
对象。要解决此问题,您必须确保this
关键字实际写入onclick
属性。
var elems = document.getElementsByClassName('test');
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = myJavascriptFunc;
}
function myJavascriptFunc() {
alert(this.getAttribute('data'));
}
&#13;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href="#" class="test" data="FooBar_1">FooBar_One</a><br>
<a href="#" class="test" data="FooBar_2">FooBar_Two</a><br>
<a href="#" class="test" data="FooBar_3">FooBar_Three</a>
</body>
</html>
&#13;
一种看待差异的方法:
<element onclick="myJavascriptFunc()">
。 // this
引用window
对象,因为元素不会被传递。
<element onclick="alert(this.getAttribute('data'));">
。 // this
指的是元素。