如何返回锚标记的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();
});

最佳答案

您有几种选择:

this引用作为参数传递给函数:

function getAnchor(el) {
    console.log($(el).data('test'));
}

$('a').on('click', function(e){
    e.preventDefault();
    getAnchor(this);
});


Example fiddle

使用call设置正在执行的函数的上下文:

function getAnchor() {
    console.log($(this).data('test'));
}

$('a').on('click', function(e){
    e.preventDefault();
    getAnchor.call(this);
});


Example fiddle

提供该函数对click处理程序的引用:

function getAnchor(e) {
    e.preventDefault();
    console.log($(this).data('test'));
}

$('a').on('click', getAnchor);


Example fiddle

关于javascript - jQuery函数返回调用者的数据值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35089200/

10-12 07:40
查看更多