2017-07-28 87 views
-3

我運行的是以下幾點:如何從字符串中剝離字符串並將其推入數組?

var countries = []; 
$("#usp-custom-3 option").each(function() { 
    var single = $(this).text(); 
    if($(single == "United States of America")) { 
    $(this).text() == "United States"; 
    } 
    countries.push(single); 
    console.log(single); 
}); 

基本上,我試圖做的是United States of America轉化爲United States之前,將其與其餘國家推入陣在一起,因爲我有個國家的名單select option

+0

也許'單== 「美國」;'?因爲單個是你傳遞給你的數組的對象 –

+0

推''(this).text()'而不是單獨的,因爲你沒有分配到'單' – Durga

+0

爲什麼downvote? –

回答

2
var countries = []; 

    $("#usp-custom-3 option").each(function() { 
    var single = $(this).text(); 
    if(single == "United States of America") { 
    single= "United States"; 
    } 
    countries.push(single); 
    console.log(single); 
    }); 
+0

非常感謝 –

0
var countries = []; 
$("#usp-custom-3 option").each(function() { 
    var single = $(this).text(); 
    if (single == "United States of America") { 
     single = "United States"; 
    } 
    countries.push(single); 
    console.log(single); 
}); 

試試這個。

+0

我仍然看到美國https:// jsfiddle。 net/pz3ce0o6/172/ –

+0

'=='不是賦值運算符。 –

0

解決了您的問題並添加了一點重構。

var countries = []; 
var us = 'United States'; 
var usa = 'United States of America'; 

$("#usp-custom-3 option").each(function() { 
    var single = $(this); //gets jquery instance of the element 
    if(single.text() == usa) { //Check if its text is USA 
    single.text(us); //Replace the option text with 'United States' 
    } 
    countries.push(single.text()); //Push value into country list 
}); 
+1

每次它會推'ua' – Durga

+0

檢查控制檯https://jsfiddle.net/pz3ce0o6/174/ –

+0

@Durga我剛​​剛注意到,也修正了。 –

1

試試這個

var countries = []; 
 
$("#usp-custom-3 option").each(function() { 
 
    var single = $(this).text(); 
 
    if (single == "United States of America") { 
 
     single = "United States"; 
 
    } 
 
    countries.push(single); 
 
    console.log(single); 
 
}); 
 

 
console.log(countries);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="usp-custom-3"> 
 
    <option>United States of America</option> 
 
    <option>India</option> 
 
    <option>UK</option> 
 
    <option>United States of America</option> 
 
    <option>India</option> 
 
    <option>UK</option> 
 
    <option>United States of America</option> 
 
</select>

0

我一直想知道爲什麼它是如此重要,只爲使用jQuery的緣故混合使用jQuery代碼。

這可能是這麼簡單(獲取節點,並將其與一個簡單的檢查映射到平面數組):

var nodesArray = [].slice.call(document.querySelectorAll("#some_select option")).map(function(v){return (v.innerText == 'United States of America') ? 'United States' : v.innerText}); 
console.log(nodesArray.toString()); 
0

$(本)的.text()==「美國」;是問題的路線。 「012」是比較表達式,不是賦值表達式。

分配值,這只是使用$(本)的.text( 「任何你想要的文字」)