1

Possible Duplicate:
What is the difference between the different methods of putting JavaScript code in an <a>?

What's different between

<a href="javascript:jsFunction();">test</a>

and

<a href="javascript:void(0);" onclick="javascript:jsFunction();">test</a>

Thank you very much.

Community
  • 1
  • 1
Phatsin.lk
  • 1,306
  • 1
  • 11
  • 8

3 Answers3

3

The first is only available for the a tag. It's a link, interpreted by your browser as javascript.

The second is a DOM Event and available for all tags.

CosminO
  • 5,018
  • 6
  • 28
  • 50
Thibault Henry
  • 816
  • 6
  • 16
1

The first is a link using the javascript protocol to tell the browser to execute everything after that as JavaScript, rather than trying to load the resource that it points to.

On the other hand, the onclick attribute is an actual JavaScript event handler, and shouldn't be used with javascript: at the beginning - it already knows that it's JavaScript so doesn't need to be told to execute it as JavaScript.

However, in the interests of separating out your content (HTML) and functionality (JavaScript), it's better to use neither of the above techniques, and instead add (for example) id attributes to identify your elements and then use JavaScript to bind your event handlers.

HTML:

<a href="#" id="test-anchor">test</a>

JavaScript:

document.getElementById('test-anchor').onclick = function(event) {
    jsFunction();
}
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
1

not this @param

<a href="javascript:jsFunction(this);">test1</a>

success this @param

<a href="javascript:void(0);" onclick="javascript:jsFunction(this);">test2</a> 


function jsFunction($this) {

    return $this; // not href  attribute this @param ; onClick attribute success  this @patam
}
yasaricli
  • 2,433
  • 21
  • 30