通过数组和具有属性的对象进行迭代

时间:2012-12-11 15:47:13

标签: javascript raphael qtip2

我不确定问题的标题是否正确。看一下代码:

var trails = new Array(trail1, trail2, trail3, trail4, trail5, trail6, trail7, trail8, trail9, trail10, trail11, trail12, trail13);
    var circles = new Array(circle1, circle2, circle3, circle4, circle5, circle6, circle7, circle8, circle9, circle10, circle11, circle12, circle13);
    var texts = new Array(text1, text2, text3, text4, text5, text6, text7, text8, text9, text10, text11, text12, text13);
    for(var i=0;i<=13;i++) {
        $([trails[i].node,circles[i].node,texts[i].node]).qtip({
        content: {
            text: 'test qtip',
            title: {text: 'test', button: 'close'}
        },
        position: {
            target: 'mouse',
            adjust: {mouse: false}
        },
        show: {
            event: 'click'
        },
        style: 'qtip-rounded qtip-shadow qtip-blue',
        hide: {
            event: 'click '
        }
    });
    }

在这个例子中,我调用另一个数组中的数组元素,所以我不确定它是否正确,但是否则.qtip在点击circle [i]或text [i]时不显示,但仅在onclick上小道[i]。还有一个.node属性,这使得这个问题对于初学者来说要复杂得多。有任何想法如何改进代码使其工作?

1 个答案:

答案 0 :(得分:0)

首先:你的循环有&#39;&lt; =&#39;您的数组包含13个项目,&#39;&lt; =&#39;将迭代14次可能导致您遇到的任何错误...

只是为了清理代码......(这部分是任意的)

var trails = [],circles = [],texts = [], i = 13;
while (i--){
    trails[i] = eval('trail'+i);//parses the text to return your js variable
    circles[i] = eval('circle'+i);
    texts[i] = eval('text'+i);
    . . .
    /** Continue with whatever else you wish to do inside the loop,
     *  I just included this bit to show how you can instantiate your
     *  arrays without having to hard code each of your variables...
     *  Also, it is possible to use the variables name as a reference
     *  inside the array like so: trails['trail'+i] = . . . 
     *  that way you can still call each variable by name. 
     */
}

就像小费一样,js在使用关键作品时会变得暴躁起来&#39; new&#39;对于数组,请使用&#39; []&#39;相反,你可以在这里阅读原因:W3Schools.com - JS - Best Practices