Reputation: 21499
I'm trying to understand 2 different lines of code below. My javascript is weak, trying to improve it with jquery (hmmmm)
What I'm trying to use the drag sort plugin from http://dragsort.codeplex.com/ specifically I'm using the http://dragsort.codeplex.com/SourceControl/changeset/view/74794#1025059 example.
I've gotten to the stage now where I've used this approach
var serialStr = "";
$("#list1 li").each(function(i, elm) {
serialStr = (i > 0 ? "|" : "") + $(elm).children().html();
});
The example has the following.
var serialStr = new Array();
$("#list1 li").each(function(i, elm) {
serialStr[] = = $(elm).attr("itemId");
});
The reason I have the first approach is that I was testing everything out and its what they had in the HTML example. I'm now trying to save the state so I've moved onto the php example.
So my question is what is the primary difference going on in the different lines here? My understanding of the first line is that its selecting each child element inside of the li tag on list1 I don't really get the (i > 0 ? "|" : "") bit.
In the second snipplet from what I understand its selecting every attribute with the itemID assignee in list1 li ?
Upvotes: 1
Views: 125
Reputation: 536349
I don't think you've pasted the code exactly as neither snippet makes sense. The first seems to want to be concatenating strings together, but is missing the +=
that would make that happen; the second is making a list, presumably to join()
together afterwards, but is using some odd []=
syntax that does not exist in JavaScript.
I don't really get the (i > 0 ? "|" : "") bit.
First time round the loop, pick ""
, subsequent times pick "|"
. This is the traditional way to make a string where each element is separated by a character.
But join()
is generally a cleaner way to do that, and you can use map()
to run a function over an array returning a new array, instead of having to manually create one:
var itemIds= $('#list1 li').map(function() {
return $(this).attr('itemId');
}).get().join('|');
(Or $(this).html()
if you really want to get the HTML content, which sounds a bit questionable.)
map()
is a jQuery function but ECMAScript Fifth Edition has a map()
method on plain arrays too. About map in general.
Upvotes: 0
Reputation: 655189
The expression (i > 0 ? "|" : "")
is using the conditional operator condition ? expr1 : expr2
to not to prefix the first value with |
but only every following values.
But the expression serialStr[] = = $(elm).attr("itemId")
is invalid syntax. Javascript does not have a push operator []
like PHP has. Use Array.prototype.push
instead.
Upvotes: 0
Reputation: 27600
serialStr[] = (i > 0 ? "|" : "") +$(elm).children().html()
is a shorthand if-clausule. It does the same as:
if(i > 0) {
serialStr[] = "|" +$(elm).children().html();
} else {
serialStr[] = "" +$(elm).children().html();
}
Upvotes: 1