0

How can I return the anchor tags' data-test value so I can use this function on anchors with different data-test values?

<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();
});
Shawn Cooke
  • 907
  • 1
  • 11
  • 28
  • 1
    Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Teemu Jan 29 '16 at 16:25
  • 3
    `e.preventDefault; //prevent anchor behaviour.` No it doesn't. You need to call it `e.preventDefault();` – A. Wolff Jan 29 '16 at 16:27

2 Answers2

2

You have several options:

Pass the this reference to the function as a parameter:

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

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

Example fiddle

Use call to set the context of the function being executed:

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

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

Example fiddle

Provide the reference of the function to the click handler:

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

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

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

the problem $(this) in your function will refer to nothing

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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' data-test='some text'>Click Me</a>
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28