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

发布于 2025-01-04 05:32:54 字数 301 浏览 2 评论 0 原文

我有代码 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独木成林 2025-01-11 05:32:54

如果您不介意使用 jQuery(如果您不介意,请忽略此答案),您可以将一个事件附加到您的链接:

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

此代码适用于键盘导航和鼠标单击: 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:

$('#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

萝莉病 2025-01-11 05:32:54

好吧...我明白这里发生了什么。问题在于,当您触发 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文