-1

I have some HTML like:

<div class="blah">
    <span class="fileName">1.jpg</span>
</div>
<div class="blah">
    <span class="fileName">2.jpg</span>
</div>
<div class="blah">
    <span class="fileName">3.jpg</span>
</div>
<div class="blah">
    <span class="fileName">4.jpg</span>
</div>

I want to get the file names with jQuery(a variable that stores smth like 1.jpg,2.jpg,3.jpg,4.jpg).

I finally could do it with an hidden input box, this is my working script:

<input type="hidden" id="img_names_input" />
<script>
$('.fileName').each(function(){
    var img_names_input = $(img_names_input).val();
    var img_names = $(this).html();
    $(img_names_input).val(img_names_input+','+img_names);
});
</script>

This is working just fine, but it doesn't seem a perfect solution to me, I'm just a learner, anybody could come up with a better solution? something like:

$('.fileName').each(function(){
        var img_names .= ',' + $(this).html();
        alert(img_names);
    });

or maybe some sort of array implementation here... !? Thanks

4

4 に答える 4

3

Use += instead of .=.

You need + to concatenate in javascript.

于 2013-03-24T08:08:53.040 に答える
1

JavaScript uses + to concatenate strings. I'd make an array:

var images = [];

$('.fileName').each(function() {
    images.push($(this).text());
});

Or with .map():

var images = $('.fileName').map(function() {
    return $(this).text();
}).get();
于 2013-03-24T08:10:47.610 に答える
1

The code should instead be like:

var img_names = "";
$('.fileName').each(function() {
    img_names += $(this).html();
});
$('#img_names_input').val(img_names);
于 2013-03-24T08:11:33.167 に答える
0

This try this snippet. Might help you.

$(document).ready(function() {
    var img_names = [];
    $('.fileName').each(function(index){
        img_names.push($(this).html());     
    });
    alert(img_names);
});

Please note that .= wont work in javascript.

于 2013-03-24T08:17:37.760 に答える