我有这段代码:
( function() {
var i, ii, e = Elements.Select('.drop');
for ( i = 0, ii = e.length; i < ii; i++ ) {
e [ i ].onclick = function () {
alert ( e [ i ].getAttribute('data-open') );
}
}
})();
我所做的是点击一个带有className'drop'的元素,然后提醒我点击的元素的属性。但是不起作用。
这段代码是我用来通过className选择元素的代码。 不要太注意,它只是向我们展示如何选择元素。
(function() {
Select : function ( element ) {
var object, index = element.substr( 0, 1 ), name = element.substr( 1, element.length ), clases = [ ], i, all = document.body.getElementsByTagName("*");
switch ( index ) {
case '.' :
for ( i = 0; i < all.length; i ++ ) {
if ( all [ i ].className == name ) {
clases.push( all [ i ] );
}
}
object = clases;
break;
return object
}
}
})();
¿答案?
答案 0 :(得分:2)
( function() {
var i, ii, e = Elements.Select('.drop');
for ( i = 0, ii = e.length; i < ii; i++ ) {
e [ i ].onclick = function () {
//by the time that this gets executed, the for loop is ended, thus i equals ii
// instead of using e[i]... try using this :
alert (this.getAttribute('data-open'));
alert ( e [ i ].getAttribute('data-open') );
}
}
})();
答案 1 :(得分:0)
你可以使用jquery。这里,'this'关键字为你提供了点击的当前元素。此类函数在类名为“drop”的任何元素的click事件上触发。
$(".drop").click( function(){
var x=$(this).attr("data-open");
});