[英]Is there a better (more efficient) way to run an href?
I was wondering if there's a better way to execute a link's href attribute other than evaling it? 我想知道除了评估它之外是否有更好的方法来执行链接的href属性?
For example: 例如:
eval($("a[href^=javascript:]").attr("href").replace(/^javascript:/,"")); // better (more eficient) way to do this?
Thanks!! 谢谢!!
If you're talking about arbitrary JS code embedded in a href="javascript:window.open('blah')"
style link, then not really. 如果你在谈论嵌入在
href="javascript:window.open('blah')"
样式链接中的任意JS代码,那么不是真的。
You should clarify the question though - hrefs
on anchor tags are really meant to be links to other documents, and you don't run them, you navigate to them. 您应该澄清这个问题 - 锚标签上的
hrefs
实际上是指向其他文档的链接,而您不运行它们, 导航到它们。 All you're really asking in your question is how to execute arbitrary javascript code supplied as a string, which is both more accurate and makes the answer clearer. 您在问题中真正提出的问题是如何执行作为字符串提供的任意javascript代码,这样更准确并使答案更清晰。 (If you try to
eval
a standard URL href attribute, nothing interesting will happen.) (如果您尝试
eval
标准URL href属性,则不会发生任何有趣的事情。)
If you did mean "how do I get the same behaviour that would happen if I clicked on this link", then that's pretty complex. 如果你的意思是“我如何获得与点击此链接时相同的行为”,那么这非常复杂。 There's no specific way to do it, so you have to try to emulate the effects by reading the attributes of the link and synthesizing an equivalent action in Javascript.
没有特定的方法可以做到这一点,因此您必须尝试通过读取链接的属性并在Javascript中合成等效操作来模拟效果。 If you forget to inspect the
target
attribute, for example, this just won't work the same, and I'm sure there are lots of other pitfalls too. 例如,如果您忘记检查
target
属性,这将无法正常工作,我相信还有很多其他陷阱。
Javascript should execute in the url bar as well, not unlike a bookmarklet. Javascript也应该在url栏中执行,与bookmarklet不同。 Try setting it to window.location without removing the 'javascript:'
尝试将其设置为window.location而不删除'javascript:'
window.location = el.attr("href");
If you're trying to execute Javascript on an a
tag, it's better to use an onclick
attribute on the a
tag in the first place. 如果你想上执行JavaScript的
a
标签,它是更好地使用onclick
的属性, a
摆在首位的标签。 That way you can do $("a#whatever-link").click();
这样你就可以做
$("a#whatever-link").click();
to get the same result. 得到相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.