Alex
Alex

Reputation: 65934

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?

For example:

eval($("a[href^=javascript:]").attr("href").replace(/^javascript:/,"")); // better (more eficient) way to do this?

Thanks!!

Upvotes: 1

Views: 100

Answers (3)

Michael Louis Thaler
Michael Louis Thaler

Reputation: 1874

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.

Upvotes: 0

Nick
Nick

Reputation: 9850

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");

Upvotes: 2

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

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.

Upvotes: 2

Related Questions