JS - 拆分字符串并循环结果 [英] JS - Splitting a string and looping through results

查看:156
本文介绍了JS - 拆分字符串并循环结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS中,我在解决如何拆分来自AJAX调用的字符串时遇到了麻烦。

In JS, I'm having trouble working out how to split a string coming from an AJAX call.

这是我到目前为止所做的:

This is what I have so far:

xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
feedUpdateResponse = xmlhttp.responseText;
/////...split script.../////
}
}
xmlhttp.open("GET","https://myDomain.com/myScript.aspx",true);
xmlhttp.send();

你有/////...split脚本... /////在上面的脚本中,我需要添加一个小函数来分割从我的AJAX调用返回的字符串。

Where you have /////...split script...///// in my script above, I need to add a little function that splits the string returned from my AJAX call.

该字符串只包含DIV的名称,如下所示:

The string simply contains names of DIVs, like this:

feedUpdateResponse = "div1/div2/div3/div4"

我想首先用斜杠(/)拆分字符串,然后运行不同值的循环,然后对页面上的元素进行处理。

I would like to first split the string by its slashes (/) and run a loop through the different values and do stuff to those elements on my page.

为了说明我需要实现的目标,我给出了这个ASP和ASP混合的例子。 JS - 这是我可能描述它的唯一方式(并表明我有过尝试):))

To give an idea of what I need to achieve, I have given this example which is a mix of ASP & JS - it's the only way I can possibly describe it (and show that I've had an attempt) :)

MyArray = Split(feedUpdateResponse,"/")
For Each X In MyArray
documentGetElementById('updateAvailable_'+x).style.visibility="visible";
Next

在我的页面上,我有一个ASP脚本,可以生成jquery轮播,全部包含在单独的DIV。 DIV被命名为DIV1,DIV2等。例如,在DIV1中,是一个名为 updateAvailable_div1 的文本元素,它将提醒用户这个源有新的照片,请点击刷新按钮。

On my page I have an ASP script that produces jquery carousels, all contained by separate DIVs. The DIVs are named DIV1, DIV2 etc. Inside DIV1, for example, is a text element called updateAvailable_div1 which will alert the user "There are new photos available for this feed, please click the refresh button".

有人可以向我解释我如何改变上面的例子来使用JS吗?只需要将字符串拆分为数组并循环遍历拆分值...

Could somebody please explain to me how I can change my example above to work in JS? Just need to split the string into an array and loop through the split values...

推荐答案

您可以使用 .split() 在指定字符上拆分字符串,并将结果作为数组返回。那么这只是循环数组的问题:

You can use .split() to split a string on a specified character with the results returned as an array. So then it's just a matter of looping through the array:

// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:

var a = feedUpdateResponse.split("/"),
    i;

for (i = 0; i < a.length; i++) {
    document.getElementById("updateAvailable_" + a[i]).style.visibility
                                                                 = "visible";
}

这篇关于JS - 拆分字符串并循环结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆