JQUERY $(element, plainObject)

I ran across this article and a set of interesting jquery syntax:  $(‘<li>’, { text: formatItem(item) }).appendTo($(‘#products’));

So after stumping a few folks and searching the jquery documentation I figured out what exactly it is doing mostly.

This explains the syntax:  http://api.jquery.com/jquery/#jQuery-html-attributes

This explains why its flexibility can lead to unintended consequences…

While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( “<input>”, {size: “4”} ) calling the .size() method instead of setting the size attribute).

So why not just use attr() to add the attribute text?

http://api.jquery.com/attr/#attr-attributeName

 

 

$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, ‘data’ contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$(‘<li>’, { text: formatItem(item) }).appendTo($(‘#products’));
});
});
});

function formatItem(item) {
return item.Name + ‘: $’ + item.Price;
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s