views:

313

answers:

1

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  A: 

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

Doug Neiner
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 ...
Val
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.
bobince
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
Val
`<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.
bobince