开发者

Javascript 'this' not returning object clicked on

i have an anchor tag generated in my code behind that calls a function with

href="javascript:blah('string',this);"

I need to interact with the object but it doesn't seem to be returning the correctly. When I alert this it returns "object Window" and calls to this.id return undefined (the anchor has an ID)

any ideas?

开发者_JS百科

Thanks


Instead of using the href for your click event use an inline onClick handler. This will give you the proper "this" object.

<a href="javascript:void(0);" onclick="blah('string',this);">


What browser are you using? Is the example href what you're trying to generate or what appears in the source code?

Assuming the link is generated correctly, this is entirely a JavaScript question.

Different browsers have slightly different implementations of event handlers. Consider using JQuery to gloss over these inconsistencies and give yourself a much easier job.


href="javascript:blah('string',this);"

inside function blah this refer to window object

do this

<a href="javascript:" id="myLink">


function handle()
{
// this refers to your link
}
document.getElementById('myLink').onclick=handle;


You can also get everything working even if javascript is disabled.

<a href="#objectToInteractWithOrAnUriWithoutTheHash" onclick="return blah(this);">test</a>


<script type="text/javascript">
   function blah(link) {
      var elementIdOrUri = link.href;

      //do some crazy stuff.

      //false will prevent the browser from visiting the link
      return false;
     }
</script>

Since you are using a href in this case, the element (if it got an anchor) or the uri will be visited if javascript is disable. Your function will be invoked otherwise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜