简体   繁体   English

使用href在javascript函数中传递此参数

[英]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> <a href="javascript:someFunction(this);" tabindex="0">Some text</a>

Is it possible to pass element into someFunction(link) {...} and use it later. 是否可以将元素传递到someFunction(link) {...}并在以后使用。

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. 当我使用像<a onClick="javascript:someFunction(this);类的onClick属性时<a onClick="javascript:someFunction(this);它工作正常。

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. 问题在于,当您触发onclick事件时,会涉及到一个元素。 Thus you can pass this and reference it in the function. 因此,你可以通过this和功能引用它。 But when you use href , you are setting the current location to whatever is in that href . 但是,当您使用hrefhref当前位置设置为该href任何内容。 It's the same as if you typed it in the address bar and hit enter. 就像您在地址栏中输入内容并按Enter键一样。 Therefore, if you pass that function this , it's actually referring to the DOMWindow object. 因此,如果您传递该函数this ,则实际上是在引用DOMWindow对象。 The only way around it that I can see, is to instead pass the node's id to the function as plain text. 我看到的唯一解决方法是改为将节点的id作为纯文本传递给函数。 Then grab it with getElementById . 然后使用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: 如果您不介意使用jQuery(否则请忽略此答案),可以将事件附加到链接:

$('#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 . 该代码可用于键盘导航和鼠标单击: http : //jsbin.com/ufapor You can see the source code here: http://jsbin.com/ufapor/edit#javascript,html 您可以在此处查看源代码: http : //jsbin.com/ufapor/edit#javascript,html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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