添加多个var

时间:2014-05-25 21:19:04

标签: javascript jquery

我有一个代码可以根据网址中的字符串生成文本。

if (keys[1].match(/q1=Other/))
{
    $("#linkdiv1").append(nextLink1);
}

当我有两个var时,代码似乎起作用,文本弹出正确的url字符串。这是在行动:

使用字符串:http://jsfiddle.net/LbKmf/8/show/?q1=Other 没有字符串:http://jsfiddle.net/LbKmf/8/

当我有两个以上的var时,代码似乎不再起作用了。这是为什么?这是代码:

使用字符串:http://jsfiddle.net/2tXvh/5/show/?q1=Other 没有字符串:http://jsfiddle.net/2tXvh/5/

为什么代码不能使用两个以上的变量,我该如何解决?

1 个答案:

答案 0 :(得分:1)

如果你按下了" tidyUp"在JSFiddle的按钮中,你会看到你的if else嵌套被另外的关闭括号和&括号中。

应该是:

$(function () {
    var url = "http://google.com/";
    var nextLink1 = "<p>State the model of your device below</p>";
    var nextLink2 = "<p>State the name of your device below</p>";
    var nextLink3 = "<p>State your devices series below</p>";
    var nextLink4 = "<p>State your devices carrier below</p>";
    var nextLink5 = "<p>State your devices capacity below</p>";

    var keys = window.location.href.split('?'); // retrieve current hash value (fragment identifier)
    if (keys[1].match(/q1=Other/)) {
        $("#linkdiv1").append(nextLink1);
    } else if (keys[1].match(/q2=Other/)) {
        $("#linkdiv2").append(nextLink2);
    } else if (keys[1].match(/q3=Other/)) {
        $("#linkdiv3").append(nextLink3);
    } else if (keys[1].match(/q4=Other/)) {
        $("#linkdiv4").append(nextLink4);
    } else if (keys[1].match(/q5=Other/)) {
        $("#linkdiv5").append(nextLink5);
    }
});

JSFiddle:http://jsfiddle.net/2tXvh/6/

就个人而言,当您开始重复硬连线代码时,您应该考虑使用数据驱动它。例如使用data-属性来保存其他数据。