如何返回锚标记'data-test
值,以便我可以在具有不同data-test
值的锚点上使用此函数?
<a href='#' data-test='some text'></a>
function getAnchor(){
// do stuff
console.log($(this).data('test'));
}
$('a').on('click',function(e){
e.preventDefault; //prevent anchor behaviour.
getAnchor();
});
答案 0 :(得分:2)
您有几种选择:
将this
引用作为参数传递给函数:
function getAnchor(el) {
console.log($(el).data('test'));
}
$('a').on('click', function(e){
e.preventDefault();
getAnchor(this);
});
使用call
设置正在执行的函数的上下文:
function getAnchor() {
console.log($(this).data('test'));
}
$('a').on('click', function(e){
e.preventDefault();
getAnchor.call(this);
});
向click
处理程序提供函数的引用:
function getAnchor(e) {
e.preventDefault();
console.log($(this).data('test'));
}
$('a').on('click', getAnchor);
答案 1 :(得分:0)
您的函数中的问题 window.addEventListener("keydown", function(e){
switch( e.keyCode ) {
case 37: // left
xmove = -0.05;
break;
case 39: //right
xmove = 0.05;
break;
case 32:
xmove = 0.01;
ymove = 0.3;
for(r = 0; r < 4; r++){
vertices[r][0] +=xmove;
for(t = 0; t < 4; t++){
vertices[r][t] +=ymove;
}}
break;
}
for(i=0; i<4; i++) {
vertices[i][0] += xmove;
}
gl.bufferSubData(gl.ARRAY_BUFFER, 0, flatten(vertices));
} );
将引用任何内容
$(this)
function getAnchor(element){
//do stuff
console.log($(element).data('test'));
}
$('a').on('click',function(e){
e.preventDefault(); //prevent anchor behaviour.
getAnchor($(this)); // or getAnchor(this);
});