简体   繁体   中英

Pass this parameter in javascript function using href

I have code <a href="javascript:someFunction(this);" tabindex="0">Some text</a> <a href="javascript:someFunction(this);" tabindex="0">Some text</a>

Is it possible to pass element into someFunction(link) {...} and use it later.

In debug mode I see the object but all properties are undefined .

When I was using onClick attribute like <a onClick="javascript:someFunction(this); it worked fine.

I am aware that this is probably not the best solution and I have seen the other questions, but it is really not my issue right now. I just need to do it this way for many reasons.

Thanks a lot

Ok... I see what has happened here. The problem is that when you trigger an onclick event, there is an element involved. Thus you can pass this and reference it in the function. But when you use href , you are setting the current location to whatever is in that href . It's the same as if you typed it in the address bar and hit enter. Therefore, if you pass that function this , it's actually referring to the DOMWindow object. The only way around it that I can see, is to instead pass the node's id to the function as plain text. Then grab it with getElementById .

I would highly recommend reconsidering how you are doing this though.

If you don't mind using jQuery (disregard this answer if you don't), you can attach an event to your link:

$('#id_of_your_link').on('click', function(event) {
  event.preventDefault();
  someFunction(this);
});

This code works for both keyboard navigation and mouse clicking: http://jsbin.com/ufapor . You can see the source code here: http://jsbin.com/ufapor/edit#javascript,html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM