doujia7094 2016-08-15 16:28
浏览 135
已采纳

从jQuery中的动态变量加载数据

first of all I must say that I've already read all the existing similar questions on this topic in SO. But unfortunately none helped me. So, please read the full question before telling it is a duplicate question, as it is not.

My Situation

I'm using a jQuery script in a wordpress plugin I'm working on. Now I'm using localize script of wordpress to pass variables to the jquery so that I can access it.

Now lets say they are like this:

  • example.src1_org

  • example.src1_new

and so on...

now inside my jquery I want to do things like this:

for (i=1; i<=example.number; i++) {
console.log("example.src" + i + "_org");
console.log("example.src" + i + "_new");
}

Now obviously it is returning the string but not the data in console.log. I've also tried window["example.src" + i + "_org"] as mentioned in some SO articles, but it didn't worked.

In javascript, generally eval() does the work. But I am not sure how to do it in jquery.

Also I've seen in most answers of SO, people are suggesting to use array. But in my case, I really don't wanna go that way as it will make my script even more complicated. It is already complicated enough.

So, it would be really help if any of you can tell me how I can access value from dynamically named variables inside jQuery, without using array.

  • 写回答

2条回答 默认 最新

  • duanqiao1947 2016-08-15 16:41
    关注

    Try:

    for (i=1; i<=example.number; i++) {
      console.log(example["src" + i + "_org"]);
      console.log(example["src" + i + "_new"]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?