我有代码 Some text
是否可以将元素传递到 someFunction(link) {...}
并稍后使用。
在调试模式下,我看到该对象,但所有属性都是未定义。
当我使用像
我知道这可能不是最好的解决方案,而且我已经看到了其他问题,但这确实不是我现在的问题,我只是需要这样做,
非常感谢。
I have code <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
发布评论
评论(2)
如果您不介意使用 jQuery(如果您不介意,请忽略此答案),您可以将一个事件附加到您的链接:
此代码适用于键盘导航和鼠标单击: http://jsbin.com/ufapor。您可以在此处查看源代码: http://jsbin.com/ufapor/edit#javascript,html
If you don't mind using jQuery (disregard this answer if you don't), you can attach an event to your link:
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
好吧...我明白这里发生了什么。问题在于,当您触发 onclick 事件时,会涉及到一个元素。因此,您可以传递
this
并在函数中引用它。但是,当您使用href
时,您会将当前位置设置为该href
中的任何位置。这与您在地址栏中输入并按 Enter 键的效果相同。因此,如果您传递该函数this
,它实际上引用的是 DOMWindow 对象。我能看到的唯一解决方法是将节点的 id 作为纯文本传递给函数。然后使用getElementById
获取它。我强烈建议您重新考虑一下您是如何做到这一点的。
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 usehref
, you are setting the current location to whatever is in thathref
. It's the same as if you typed it in the address bar and hit enter. Therefore, if you pass that functionthis
, it's actually referring to the DOMWindow object. The only way around it that I can see, is to instead pass the node'sid
to the function as plain text. Then grab it withgetElementById
.I would highly recommend reconsidering how you are doing this though.