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

Val
  • 17,336
  • 23
  • 95
  • 144

2 Answers2

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

Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
  • 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 – Val Jan 13 '10 at 22:15
  • 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 Jan 13 '10 at 22:16
  • 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 `` this is always blocked for security reasons... so it's my only way to make it possible i guess – Val Jan 13 '10 at 22:23
  • ` – bobince Jan 13 '10 at 23:58
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!

Gago Ar
  • 97
  • 1
  • 3