开发者

JavaScript substr on jQuery html() of a JavaScript variable

What I'm trying to ask is that when I take on a .each loop in jQuery using a build of a string by this:

$('.list :checkbox').each(function()
{
    var type = $(this).attr('value');
    Build += type + ', ';

    return Build;
});

But now I need to remove the last "," (without quotes) since it makes a list like this:

Item 1, Item 2, Item 3, Item 4, Item 5,

Then it has to be added to the html() function which 开发者_C百科works well, but when trying to remove the last "," doesn't work by doing this:

Build.substr(-1);

$('#list-box').html(Build);

But that won't work.


You could simplify your code with something like this:

(updated)

var arr = $(":checkbox").map(function() {
    return this.value;
}).get();


$('#list-box').html(arr.join(","));

Try it here: http://jsfiddle.net/andrewwhitaker/rXB2K/ (also updated)

  • Uses the map() function to translate the jquery results array to an array of checkbox values.
  • Calls join(), separating each value with a comma.


@YouBook: Try

Build.substr(0, Build.length - 1);

instead.


Have you tried using substring instead of substr? e.g.

Build.substring(Build.length - 1);


Build = Build.slice(0,-1);

works?


Instead this:

return Build;

write this:

return Build.substr(0, Build.length-1);


Don't use initial caps for variables.

Also, Strings are immutable in JS, so it's

   build = build.substring(0, b.length-1)

This is a general purpose function called join in most languages, you should break it out as a utility function.

You should take into account the possibility of a zero length list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜