如何获取href javascript函数中的调用者元素? [英] how to get the caller element in href javascript function?

查看:118
本文介绍了如何获取href javascript函数中的调用者元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < a href =javascript:handleEvent(this ,'abc')>< / a> 

现在在javascript函数中,我写了:

 函数handleEvent(sourceElement,txt){
console.log(sourceElement);
}

在这种情况下,控制元素即将作为窗口。
我尝试了sourceElement.document.activeElement,但它似乎不能在chrome中使用,它是以body元素的形式出现的。



我无法更改将标记锚定到'onClick'函数,因为它来自其他来源。
在这种情况下是否有一些方法可以找到调用元素?

解决方案

这里真正的答案是更改HTML,你说过你不能这样做。如果可以的话,我会推回来的。如果你正在编写函数,并且函数名称是在HTML中,那么你怎样才能改变HTML?



但是如果你真的,真的不能,你可以在加载后更新DOM:

  var list = document.querySelectorAll('a [href ^ = JavaScript的:]'); 
var x,link;
for(x = 0; x link = list [x];
link.onclick = new Function(link.href.substring(11));
link.href =javascript :;;
}

实时复制 | Live Source



这相当淘气,因为它使用 Function 构造函数(非常类似于 eval ),但 if 你相信HTML的来源,那应该没问题。



或者当然,如果你不需要使用 href 首先,在上面的代码中挂上你的事件处理程序,不要使用 new Function


I have an anchor tag element coming in the html like:

<a href="javascript:handleEvent(this, 'abc')"></a>

Now in the javascript function, I have written:

function handleEvent(sourceElement, txt) {
    console.log(sourceElement);
}

the consoled element is coming as the window in this case. I tried sourceElement.document.activeElement but it doesnt seem to work in chrome, where it is coming as body element.

I cannot change the structure of the anchor tag to 'onClick' function as this is coming from some other source. Is there some way to find the calling element in this scenario?

解决方案

The real answer here is to change the HTML, which you've said you can't do. I'd push back on that if you can. If you're writing the function, and the function name is in the HTML, how is it you can't change the HTML??

But if you really, really can't, you can update the DOM once it's loaded:

var list = document.querySelectorAll('a[href^="javascript:"]');
var x, link;
for (x = 0; x < list.length; ++x) {
    link = list[x];
    link.onclick = new Function(link.href.substring(11));
    link.href = "javascript:;";
}

Live Copy | Live Source

This is fairly naughty, as it uses the Function constructor (which is very much like eval), but if you trust the source of the HTML, that should be okay.

Or of course, if you don't have to use whatever was in the href to start with, just hook up your event handler in the code above and don't use new Function.

这篇关于如何获取href javascript函数中的调用者元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆