简体   繁体   English

如何使用Javascript将元素的内部HTML文本替换为数组的一部分

[英]How to replace inner HTML text of an element with part of an array using Javascript

I'm taking a JavaScript class and for an exercise we have to compare an array to another array, and replace the inner html text of an element with only the string values that exist in BOTH arrays. 我正在学习一个JavaScript类,为了进行练习,我们必须将一个数组与另一个数组进行比较,并用两个数组中都存在的字符串值替换元素的内部html文本。 Here is the javascript: 这是JavaScript:

// Here is an array of US State Capitals to use
var capitals = ["Montgomery", "Juneau", "Phoenix", "Little Rock", "Sacramento", "Denver", "Hartford", "Dover", "Tallahassee", "Atlanta", "Honolulu", "Boise", "Springfield", "Indianapolis", "Des Moines", "Topeka", "Frankfort", "Baton Rouge", "Augusta", "Annapolis", "Boston", "Lansing", "Saint Paul", "Jackson", "Jefferson City", "Helena", "Lincoln", "Carson City", "Concord", "Trenton", "Santa Fe", "Albany", "Raleigh", "Bismarck", "Columbus", "Oklahoma City", "Salem", "Harrisburg", "Providence", "Columbia", "Pierre", "Nashville", "Austin", "Salt Lake City", "Montpelier", "Richmond", "Olympia", "Charleston", "Madison", "Cheyenne"];



// Using JavaScript, get the contents of the "cities" div and convert it into an array of strings (each city will be an element in the array)
var citiesString = document.getElementById("cities").innerHTML;

var cities = citiesString.split(", ");


// Loop through the array of cities.  Compare each element to the array of capitals.  If a city is NOT a state capital, update the HTML output to leave out that city.  (Note: formatting, commas, etc. doesn't count -- just get the cities to display.)


for (i = 0; i < cities.length; i++) {
  if(capitals.indexOf(cities[i]) >=0) {
    document.getElementById("cities").innerHTML += cities[i] += ", ";
  } 
}

I have it displaying only the cities present in both arrays, but it is still displaying the entire list of the cities array before hand. 我只显示两个阵列中都存在的城市,但它仍在显示之前城市阵列的整个列表。 How do I get it to display only "Boston, Indianapolis, and Atlanta"? 我如何只显示“波士顿,印第安纳波利斯和亚特兰大”?

clear the content of the 'cities' before the for loop. 在for循环之前清除“城市”的内容。

document.getElementById("cities").innerHTML = "";

you were appending your your array to the existing text in your element. 您将数组追加到元素中现有的文本上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM