fsi
fsi

Reputation: 1367

On $.each pass object in function

I'm having trouble with passing object to a function and append to a page. Is it really necessary to use prototype? From this link helped me to understand a bit, but still no success.

on my $.each, will add some markers by server and thoses markers will have a link go to a page to give a description about the place. the x is my object and description is that I want to append it.

$.each(data, function (i, x) {
    var alerts = '<button type="button" onclick="getInfo(' + x + ')">AAAA YEAHHH</button>';
}

function getInfo(x) {
...//go to a page and append it
    $('#about-info').append(x.description);
}

Upvotes: 0

Views: 84

Answers (2)

Chris Moutray
Chris Moutray

Reputation: 18349

You could attach the click handler like this instead:

$.each(data, function (i, x) {
    $('<button type="button">AAAA YEAHHH</button>').on('click', function () {
        getInfo(x);
    }).appendTo('body');
}

OR

Since you know the property is x.description just you the value directly like this

$.each(data, function (i, x) {
    var alerts = '<button type="button" onclick="getInfo(\'' + x.description + '\');">AAAA YEAHHH</button>';
}

An Explanation of \'' + x.description + '\'

Well

  • ... \' is escaping the single quote so that it can be included as a literal value in the javascript string that you're creating.
  • The next single quote ends the string that was originally started '<button ....
  • + x.description + is concatenating the value of the description property - we're not passing x or a reference of x.description into getInfo but instead calling getInfo with whatever x.description contains at the time the string assigned to alerts was created.
  • '\' ... Here the first single quote starts a new string and then as the first character of that string includes a single quote as a literal value (ie escaping the single quote like this \')

In javascript you can use either double or single quotes to create strings so as an alternative you could have done this

var alerts = "<button type=\"button\" onclick=\"getInfo('" + x.description + "');\">AAAA YEAHHH</button>";

but again since we're using double quotes to create our string we have to escape the double quotes that we want to include in the string like this \"

Upvotes: 2

Chris Pietschmann
Chris Pietschmann

Reputation: 29885

You'll need to build the html button element with code.

$.each(data, function(i, x) {
    var localx = x,
        btn = $('<button/>').attr('type','button').click(function(){
            getInfo(localx);
        }).text('AAAA YEAHHH');
    // add btn to the page somewhere here
});

function getInfo(x) {
    $('#about-info').append(x.description);
}

Upvotes: 0

Related Questions