变量破坏了我的代码 [英] A variable is breaking my code

查看:98
本文介绍了变量破坏了我的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我开发的网站构建自定义计算器.我是一名新开发人员,这有点麻烦,但是我正在尝试学习.

I am trying to build a custom calculator for a website I develop. I am a new developer and this is a bit over my head but I am trying to learn.

我试图获取2个变量并将其合并为1,然后使用该变量通过ajax从另一个页面调用div.好吧,我遇到的问题是,当我添加代码以合并两个var时,它会使分页符中断,我不确定为什么.

I am trying to grab 2 variables and combine them into 1 and then use that to call a div from another page through ajax. Well the problem I am having is that when I add the code to combine the 2 vars, it makes the page break and I am not sure why.

     $(function(){
        $("input:radio[name=f_1]").click(function() {
          var type = $(this).val();
        });
        $("input:radio[name=f_1a]").click(function() {
          var prod = $(this).val();
        });

        var JobType = type + prod;
    });

您可以在此处实时查看它: http://rdmproductions.com/dev/

You can see it live here: http://rdmproductions.com/dev/

如果将JobType变量用作一行,则页面将按其应有的方式工作.我只是不了解发生了什么以及如何解决.

if you take the line for the JobType variable, the page will act as it should. I just don't understand what's happening and how to fix it.

推荐答案

您的变量typeprod是局部变量,因此在单击处理程序回调函数之外不可用.

Your variables type and prod are local variables so they are not available outside the click handler callback functions.

如果希望它们在这些单击处理程序之外可用,则需要在更高级别的范围内声明它们或将其存储在其他超出单击处理程序功能寿命的对象中.

if you want them to be available outside those click handlers, then you need to declare them at a higher level scope or store them in some other object that is persistent beyond the life of your click handler function.

可能要做的是在需要时获取type和prod的值,而不是尝试将它们保留在JobType中.

Probably what you want to do is fetch the values of type and prod when you need them rather than try to keep them in JobType.

您可以按需获取数据,如下所示:

You could fetch the data upon demand like this:

var JobType = $("input:radio[name=f_1]").val() + $("input:radio[name=f_1a]").val();

您甚至根本不需要两个单选按钮上的点击处理程序.

You wouldn't even need the click handlers on the two radio buttons at all.

根据您的最新评论进行

您可以侦听两个无线电组的更改,检查两个无线电组均已选中,然后使用类似以下代码的组合值来做一些事情:

You can listen for changes to both radio groups, check when both have been selected and then do something with the combined value using code like this:

$("input:radio[name=f_1], input:radio[name=f_1a]").change(function() {
    var f1 = $("input:radio[name=f_1]:checked").val();
    var f1a = $("input:radio[name=f_1a]:checked").val();
    if (f1 && f1a) {
        // both radio buttons have been selected, do something here
        var jobType = f1 + f1a;
        // do something with jobType here
        alert(jobType);
    }
});

您可以在这里看到它的工作: http://jsfiddle.net/jfriend00/FJcTA/

You can see it work here: http://jsfiddle.net/jfriend00/FJcTA/

这篇关于变量破坏了我的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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