Does anyone know an easy way to use jQuery (or other Javascript if necessary) to extract only the Javascript portion of an anchor tag's href attribute (like the one below), so it can be assigned to another 开发者_如何学JAVAevent at runtime?
<a id="FancyLink" href="javascript:DoSomething('Input1')">Do</a>
I know how to get the anchor's whole attribute value using jQuery, and I suppose I could just do that and then chop off the "javascript:" prefix manually, but I'm wondering if there is a better way to obtain a JavaScript function object from the above example.
Thanks for the help!
Brian
Like this:
var code = $('#FancyLink').attr('href').replace(/^javascript:\s*/, '');
This will return a stringm which you'll need to eval
in order to execute.
For better performance, you can call eval
once and create a function, like this:
var executor = eval('[ function() { ' + code + ' } ]')[0];
The array is necessary because IE cannot directly return a function from eval
.
For even better performance, don't do this at all.
Assuming you can't refactor the <a href="javascript:...">
code, which is the problem here, you could also assign the href to location
, which is roughly what happens when user clicks the link anyway. That would save you chopping off the 'javascript:' portion and would be a bit more natural.
精彩评论