Thursday 15 August 2013

javascript - Pushing/Creating elements dynamically in jQuery and then immediately looping through to append HTML -


I'm trying to define an area in a jQuery snippet which is easy to change the user's last goal That user defines the values, but jQuery will create objects from the list.

I start with this simple HTML div:

  & lt; Div class = "slider-container" & gt; & Lt; / Div & gt;   

followed by JS concept:

  var newSlides = []; $ ("Slider-container") Each (function () {newSlides.push ({image: {url: "http://placekitten.com/960/400", title: "sample title 1", subtitle: "sample subtitle 1"}, image: { Url: "http://placekitten.com/961/401", title: "sample title 2"};});});   

I would like to be able to take these values ​​and do this:

  var index = 1; $ ("Slider-container") Attached ($ ("
, {class:" slide s- "+ Index ++}) .append ($ (" & lt; img / & gt;, {src: "Url- From-top "})) .append ($ ("
, {class: "slide-titles"}) .append ($ ("(lt; h2 / & gt;, {class: Title "). Text (" Text-To-Top ") .append ($ (" & lt; h3 / ", {class:" subtitle "}). Text (" Text-To-Top ")) )

so that the end result will be:

  
gt;
< P> The target is that a user only has to define values ​​and there is no need to worry about defining HTML or keeping things in the right place. Easy to edit for any person

I agree with others that a smiling-like templing engine would be useful. If you want to do this directly with jQuery:

 for  (i = 0; I ) Attachment (slide); If (slide_data.title) {$ ('& lt; h2 & gt;' + slide_data.title + '& lt; / h2 & gt;') Attachment (title); } If (slide_data.subtitle) {$ ('& lt; h3 & gt;' + slide_data.subtitle + '& lt; / h3 & gt;'). Attachment (title); }}   

For the above code, you will need to modify your push () statement so that it push the object instead of pushing it directly into the array. Object contains your target object eg

  var newSlides = []; NewSlides.push ({url: "http://placekitten.com/960/400", Title: "Sample Title 1", Subtitle: "Sample Subtitle 1"}, {url: "http://placekitten.com/ 961/401 ", Title:" Sample Title 2 "});    

No comments:

Post a Comment