当前位置: 动力学知识库 > 问答 > 编程问答 >

Adding to JQuery script runtime

问题描述:

I'm working on a project where it would be very useful to be able to parse some text from e.g. a database to jQuery.

An example would be this line:

$(container).show("drop", { direction: "bottom", distance: 300 }, 800);

This works great when I hardcode it into my file - but what I would like to be able to do is store this:

.show("drop", { direction: "bottom", distance: 300 }, 800);

in e.g. a database and then retrieve it at page rendering and use it in my jQuery code.

I'm currently rendering the stored jQuery out into a hiddenfield, but whenever I try to combine the values:

$(container) + $("#hfJquery");

All I get is a text-string - which makes sense. So the question is - is there any way to append code to a jquery code block in a way so that the plain text from the hiddenfield will be treated as jQuery code and not text?

网友答案:

I don't really see the point in doing something. But take a look at eval():

http://jsfiddle.net/yP9ZL/1/

eval("$('#containerID')" + $("#hfJquery").val());
网友答案:

You could store the data as JSON. This would only occupy one field in DB.

You would then output to javascript object variable or store it in data- attributes of markup:

var data={
  "selector": "#Div",
  "animMethod": "show",
  "effect": "drop",
  "options": { "direction": "bottom", "distance": 300 },
  "duration": 800  

}

function runAnimation(data){
   $( data.selector)[ data.animMethod] ( data.effect, data.options, data.duration);

}
runAnimation(data);

The JSON could also be added directly to an element in a data- attribute

<div class="run_animation" data-animData="{animMethod: 'show'.....,  duration: 800 }">

Then retrieve from element:

$('.run_animation').each(function(){
  /* retrieve data object from markup*/
  var data=$(this).data('animData')
  $(this)[ data.animMethod] ( data.effect, data.options, data.duration);    
})
分享给朋友:
您可能感兴趣的文章:
随机阅读: