我正在运行以下内容:
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
之前将其与其他国家/地区一起推送到阵列中,因为我有一个{{1}的国家/地区列表}。
答案 0 :(得分: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);
});
答案 1 :(得分: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>
&#13;
答案 2 :(得分: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);
});
尝试这个。
答案 3 :(得分: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
});
答案 4 :(得分: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());
答案 5 :(得分:0)
$(this).text()==“United States”;是有问题的。
“==”是比较表达式而不是赋值表达式。
为此赋值只需使用$(this).text(“任何你想要的文字”)