2

is this possible?

<div id="anything">I will change</div>
<div id="id" jq="$('#anything').css({background: 'red'})"></div>

var x = '$('#id').attr('jq')';
jQuery.call(x);

Basically i would like use an attribute jq on any tag to act like a onclick would on html that calls the javascript statements.

btw jQuery.call() is for demonstration purposes it doesn't work...

2 Answers 2

9

You would use eval() but what you are doing seems like a really bad idea:

var x = $('#id').attr('jq');
eval(x);

The reason this is bad, is you are not separating function from structure. HTML is meant to describe structure, not interactivity and function.

JavaScript is meant to provide that interaction and enhancement, but not structure. Using the jQuery inline like that is a violation of that separation. Just food for thought...

Sign up to request clarification or add additional context in comments.

4 Comments

i am not sure i really understood that. all i want the jq attrbute to carry js/jQuery instructions and interpreter them as if it was written on a <script> tag... jq could always be jq="foo()" or jq="$('#anything').draggable()" or what ever you could think of ...
Indeed, part of the attraction of jQuery is that it makes it easy to write code that's nicely separated from the HTML. Putting the code back in the markup (as well as making the markup invalid at the same time) does not seem like a step forward.
well there is my problem... i am trying to use ajax with source example.html to get a page but on example.html if there is a tag <script>// jqeury code here // or javascript</script> this is always blocked for security reasons... so it's my only way to make it possible i guess
<script> tags in returned content aren't blocked as such, it's just they don't work properly across browsers. You could pass a snippet of HTML and some script as separate members of a JSON object... but still, it's questionable to be passing back and dynamically executing code IMO. It's almost always best to keep all your code static.
7

you can use new Function MDN

body:

<div id='MyFunc' func="alert('Hello!');" >On Load raise an Alert</div>

js:

var myFunc = myFunc || document.getElementById('MyFunc'),
        hello = new Function( myFunc.getAttribute('func'));
    hello.call(this);

give it a try:

http://jsfiddle.net/msLsy/

Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.