开发者

Is there a better (more efficient) way to run an href?

开发者 https://www.devze.com 2023-01-06 10:49 出处:网络
I was wondering if there\'s a better way to execute a link\'s href attribute other than evali开发者_如何学JAVAng it?

I was wondering if there's a better way to execute a link's href attribute other than evali开发者_如何学JAVAng it?

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.

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. 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. (If you try to eval a standard URL href attribute, nothing interesting will happen.)

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. 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.


Javascript should execute in the url bar as well, not unlike a bookmarklet. Try setting it to window.location without removing the '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. That way you can do $("a#whatever-link").click(); to get the same result.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号