JS文件外的JQuery vars

时间:2011-09-13 17:09:07

标签: php jquery

在我用PHP填充的头文件中:

<script type="text/javascript"> 
var packages = {};
packages[1] = {title:'Pack 1',price:7.50,setup:0.00,template:0};
packages[2] = {title:'Pack 2',price:12.00,setup:0.00,template:0};
packages[3] = {title:'Pack 3',price:25.00,setup:75.00,template:1};
var templates = {};
templates[4] = {title:'Template 1'};
templates[5] = {title:'Template 2'};
templates[6] = {title:'Template 3'};
</script>    

<script type="text/javascript" src="/include/jscript/form.inc.js"></script> 

现在在form.inc.js中我想要vars包的内容。所以喜欢:

function updatePrices(){
    var package_price = 0;
    var setup_price = 0;

    var package = $_2('#package_select').val();

    package_price += packages[package].price;
    setup_price += packages[package].setup;

    $_2(".package_price").html("&pound;"+package_price);
    $_2(".setup_price").html("&pound;"+setup_price);
    $_2(".total_price").html("&pound;"+(package_price+setup_price));
}

你在这里看到:package [package] .price包[1] .price并且应该显示7.50,但我不认为var包正在通过!

任何帮助都会很棒,谢谢

2 个答案:

答案 0 :(得分:2)

您的脚本未运行,因为它中包含语法错误:

var packages = {};
packages[1] = {title:'Book'In',price:7.50,setup:0.00,template:0};
/intake/:21SyntaxError: Parse error
packages[2] = {title:'Book'In Plus',price:12.00,setup:0.00,template:0};
packages[3] = {title:'Full Monty',price:25.00,setup:75.00,template:1};
var templates = {};
templates[4] = {title:'Template 1'};
templates[5] = {title:'Template 2'};
templates[6] = {title:'Template 3'};

请注意,您使用单引号标记标题字符串,但其中两个标题中包含单引号。你需要用斜杠来转义单引号,如下所示:

packages[1] = {title: 'Book\'In',price:7.50,setup:0.00,template:0};

请查看浏览器的JavaScript /错误控制台。它会为你做奇迹= D

答案 1 :(得分:0)

看起来你的包和模板变量是对象,我想你想要一个数组:

<script type="text/javascript"> 
var packages = [];  //square brackets instead of curly brackets create new arrays

packages[1] = {title:'Pack 1',price:7.50,setup:0.00,template:0};
packages[2] = {title:'Pack 2',price:12.00,setup:0.00,template:0};
packages[3] = {title:'Pack 3',price:25.00,setup:75.00,template:1};

var templates = []; //square brackets instead of curly brackets create new arrays

templates[4] = {title:'Template 1'};
templates[5] = {title:'Template 2'};
templates[6] = {title:'Template 3'};
</script>