Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Pass HTML with JS variable as parameter

Tags:

jquery

ajax

I have a namespace called "X" and it has a getJSON function that fetches some file from the server. I want to reuse this namespace with varying contents. Here is the code:

var uid = "27D76901-B6B1-B332-918B-D9F5A7152EFC";
var X = {
    el: "",
    elMarkup: "",
    url: "",
    initialize: function(el, elMarkup, url){
        $.getJSON(url, function(data){
            el.find("p").remove().end();
            $.each(data.comments, function(key, value){
                el.append(elMarkup);
            })
        })
    }
};

X.el = $("#comments");
X.elMarkup = "<p>"+ value.content +" by "+ value.user +"</p>";
X.url = "http://example.com/getComments?uid=" + uid;
X.initialize(X.el, X.elMarkup, X.url);

I am having a problem with the elMarkup variable for the $.each loop. How can I define this variable dynamically? Thanks!

like image 742
fart-y-goer Avatar asked Jun 11 '26 14:06

fart-y-goer


2 Answers

You could try this:

X.elMarkup = function(value) {
   return "<p>"+ value.content +" by "+ value.user +"</p>";
};

And then in your $.getJSON() callback:

        $.each(data.comments, function(key, value){
            el.append(elMarkup(value));
        });

That is, instead of defining X.elMarkup as a string, define it as a callback function that generates the particular html structure you need. Then your generic initialize() function just has to call elMarkup() and pass the current value that needs formatting.

Note that it doesn't really make sense to set the properties as X.el = ... if you're just going to pass those properties as arguments to the X.initialize() function. It would make more sense to just pass the required values directly and have X.initialize() save the values as properties if needed. Or set the properties and call X.initialize() with no arguments.

like image 103
nnnnnn Avatar answered Jun 14 '26 06:06

nnnnnn


Change the following:

$.each(data.comments, function(key, value){
    el.append(elMarkup);
})

to

$.each(data.comments, function(key, value){
    el.append($('<p />', {"html": value.content + " by " + value.user}));
})

because of the reason I mentioned in comment.

like image 29
hjpotter92 Avatar answered Jun 14 '26 06:06

hjpotter92



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!