Skip to content Skip to sidebar Skip to footer

How To Execute Function Stored As A String Without Eval()

Let me preface this question by saying there may be a completely different solution than my title so let me tell you what I am after entirely. Basically I have a series of menu lin

Solution 1:

There are a few solutions here. You might want to look into using something like Backbone which provides something called routers that would aid you in navigation.

Or to hack up something similar, set each of your href tags to point to a new # anchor:

<a href="#2">next page</a>

and then attach a listener to the hashchange event. When the event fires, the user has clicked on the link. Then access the hash window.location.hash and use that as the argument to a function which does what you need it to do.

$(window).on('hashchange', function(event){
    $('#primary').turn('page', window.location.hash.slice(1));
}

The slice is there since window.location.hash includes the # character.


EDIT

I notice you updated saying you use wordpress and you're editing out the http:// part of your URLs. If you're using the hashchange event you don't need to since href="#2" is the same as href="http://mysite.post.com/this_post/#2"

Solution 2:

How about use the onclick event?

<a onclick="function(){$('#primary').turn('page', 2); return false;}" href="#">Click me!</a>

Alternately, since you're using JQuery, you could .bind() the event:

<script>
    $('a.clickable').bind('click', function(e){
         var pageNum = $(this).attr('data-page');
         $(#primary).turn('page', pageNum);
         returnfalse;
    });
</script><body><aclass='clickable'data-page='2'href='#'>Click me!</a>

Alternately, since you only have access to the href attribute, you COULD do this, which is the easy way out:

 <a href="javascript:$('#primary').turn('page', 2)">Click me!</a>

Solution 3:

Can't you simply simulate a click event on the links in that case? In other words, if you already have jquery loaded $("a#identifier").click(). In your current scenario that seems to be the easiest way.

Solution 4:

I've a similar issue and solved it like this:

In your script, define a function like:

$.fn.DoSomething=function (MyOption){ window.alert(MyOption); };

And in your link href call the function like javascript:$.fn.DoSomething('Hello');

Post a Comment for "How To Execute Function Stored As A String Without Eval()"