如何使用 Javascript 将元素的内部 HTML 文本替换为数组的一部分
Posted
技术标签:
【中文标题】如何使用 Javascript 将元素的内部 HTML 文本替换为数组的一部分【英文标题】:How to replace inner HTML text of an element with part of an array using Javascript 【发布时间】:2018-07-30 08:51:13 【问题描述】:我正在学习一个 javascript 课程,作为练习,我们必须将一个数组与另一个数组进行比较,并仅将一个元素的内部 html 文本替换为两个数组中都存在的字符串值。这是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] += ", ";
我让它只显示两个数组中存在的城市,但它仍然事先显示城市数组的整个列表。如何让它只显示“波士顿、印第安纳波利斯和亚特兰大”?
【问题讨论】:
请显示城市内的数据 【参考方案1】:在 for 循环之前清除“城市”的内容。
document.getElementById("cities").innerHTML = "";
您将数组附加到元素中的现有文本。
【讨论】:
谢谢!我在 for 循环之前添加了这个,它现在可以工作了。以上是关于如何使用 Javascript 将元素的内部 HTML 文本替换为数组的一部分的主要内容,如果未能解决你的问题,请参考以下文章
尝试使用 chrome 控制台 javascript/jquery 获取内部元素
使用 JavaScript 如何禁用右键单击或单击滚动条时如何在右键单击窗口中删除检查元素选项
[ jquery 文档处理 append(content|fn) ] 此方法用于向每个匹配的元素内部追加内容,这个操作与javascript对指定的元素执行appendChild方法,将它们添加到文档