2013-03-24 28 views
-1

我有一些HTML一樣:如何使用= jQuery中

<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> 

我想使用jQuery(一個變量來獲取文件名,存儲不便像1.JPG,2.JPG,3.JPG ,4.JPG)。

我終於可以用一個隱藏的輸入框做了,這是我的工作腳本:

<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> 

這是工作得很好,但它似乎並沒有一個完美的解決方案給我,我只是一個學習者,任何人都可以想出更好的解決方案?像這樣:

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

或者可能某種數組實現在這裏......!? 謝謝

+1

'。='是連接在PHP – hjpotter92 2013-03-24 08:09:46

+0

爲什麼3個負面點!?它是什麼? – behz4d 2013-03-24 08:11:19

+0

['。'在PHP中](http://php.net/manual/en/language.operators.string.php)vs ['+ ='in Javascript](http://www.w3schools.com/ js/js_operators.asp) – Aiias 2013-03-24 08:11:29

回答

0

該試試這個片斷。可以幫助你。

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

請注意,JavaScript代碼.=不會工作。

+0

使用[]代替新數組並推送內容 – mplungjan 2013-03-24 08:56:50

3

使用+=而不是.=

您需要+才能在javascript中連接。

1

JavaScript使用+來連接字符串。我會做一個數組:

var images = []; 

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

或者與.map()

var images = $('.fileName').map(function() { 
    return $(this).text(); 
}).get(); 
1

的代碼應改爲如:

var img_names = ""; 
$('.fileName').each(function() { 
    img_names += $(this).html(); 
}); 
$('#img_names_input').val(img_names);