0

简短描述 我正在使用 jquery、jqueryUI 和 ajax。

我第一次完美地使用 val() 从字段中获取值,但是如果我更改字段中的值,则值保持不变。

详细描述我正在开发一个大项目我在这个项目上大约有 2 年的时间我的头在抽!;)

我有这样的事情:

这是 div 的 html:

<div id="add_task_diag" style="display: none">
   <label for="task">Task : </label><input id="taskfrm" label="Task" value="task" name="taskval" placeholder="e.g fill in tax form" />
   <button value="submit" class="btn btn-large add_task_frm">Add task</button> <button class="btn btn-large cancel_add_task">Cancel</button>
</div>
<button class="btn btn-primary" id="add_task"><i class="icon-file icon-white"></i> Add Todo</button>

这是脚本:

<script>
$(".add_task_frm").click(function() {
    function taskgen() {
        var data = "task=" + $("#taskfrm").val();
        alert(data); // only for debuging
        var task_data = data;
        alert(task_data); // only for debuging
        $.post("whereitneedtogo.php?task=action80", task_data), //this is the ajax part
        $("#add_task_diag").dialog("destroy"); // I had here close I changed it to "destroy"
        task_data = undefined; //I tried to unset the variable
    }
    taskgen();
});​
</script>

当我运行它时,一切正常!当我用另一个值重新发送时,变量保持不变。例如,如果我将 test123 放在第二个测试的字段中,它将保持 test123 我需要重新加载页面以重置变量。

我不想使用 location.reload()

该文件有 1700 多行,但这是问题所在。

我尝试了很多类似的事情: - 在 Dom 准备好后设置我的脚本 - 将我的变量设置为未定义或 null - 销毁 jquery 选项卡 - 唯一对我有用的部分似乎是 location.reload 但我的应用程序是完整的 ajax。

感谢您的帮助,我希望这是愚蠢或容易的。

4

2 回答 2

1

为什么每次单击时都尝试声明和调用该函数。尝试将其移到单击事件处理程序之外。

<script>
$(".add_task_frm").click(function() {
    taskgen();
});​

function taskgen() {
        var data = "task=" + $("#taskfrm").val();
        alert(data); // only for debuging
        var task_data = data;
        alert(task_data); // only for debuging
        $.post("whereitneedtogo.php?task=action80", task_data), //this is the ajax part
        $("#add_task_diag").dialog("destroy"); // I had here close I changed it to "destroy"
        task_data = undefined; //I tried to unset the variable
    }

</script>

当您想从其他地方调用 taskgen() 时,您可能还会遇到范围问题。

于 2012-09-28T21:10:50.737 回答
0

这是因为您在点击处理程序中定义了您的闭包。将taskgen函数移到单击处理程序之外,将所有内容都包含在内,$(document).ready()您应该一切顺利!见下文:

$(document).ready(function() {

    $(".add_task_frm").click(function() {
       taskgen();
    });

    function taskgen() {
       var data = "task=" + $("#taskfrm").val();

       alert(data); // only for debuging
       var task_data = data;
       alert(task_data); // only for debuging
       $.post("whereitneedtogo.php?task=action80", task_data), //this is the ajax part
       $("#add_task_diag").dialog("close").dialog("destroy"); // I usually chain 'close' and 'destroy'
    }

});
于 2012-09-28T21:11:29.583 回答