如何将参数传递给jQuery UI对话框事件处理程序?

我目前正在尝试连接jQuery UI对话框,以便我可以使用它来为我的页面创建新项目并修改页面上已有的项目。 我在前者管理过。 不过,我现在正在努力解决后一个问题。 我只是找不到一个很好的方法来传递项目来修改对话框。

这里有一些代码可以更好地说明问题。 请特别注意标有XXX的部分。 {{}}部分源自Django模板语法:

$(".exercise").click(function() { $.post("{{ request.path }}", { action: "create_dialog", exercise_name: $(this).text() }, function(data) { $("#modify_exercise").html(data.content); }, "json" ); $("#modify_exercise").dialog('open'); }); $("#modify_exercise").dialog({ autoOpen: false, resizable: false, modal: true, buttons: { '{% trans 'Modify' %}': function() { var $inputs = $('#modify_exercise :input'); var post_values = {}; $inputs.each(function() { post_values[this.name] = $(this).val(); }); post_values.action = 'validate_form'; //XXX: how to get the exercise name here? post_values.exercise_name = 'foobar'; $.post('{{ request.path }}', post_values, function(data) { if( data.status == 'invalid' ) { $('#modify_exercise').html(data.content); } else { location.reload(); } }, "json" ); } } }); 

这里有一些标记来显示代码与结构的关系:

 

如果您正在使用事件处理程序,您可能希望使用事件对象而不是某些全局变量;)

event.target就是你要找的东西。

例如

 $('.sel').bind('dialogcreate', function(event, ui) { event.target.innerHTML = 'new content'; }); 

也许以下可能更适合您的口味:

$("#modify_exercise").dialog('open'); ,添加

 $("#modify_exercise").data('exercise_name',$(this).text()); 

并在按钮回调中,替换post_values.exercise_name = 'foobar';

  post_values.exercise_name = $(this).data('exercise_name'); 

我想不出点击事件和对话框之间是如何联系的,所以答案可能就是在每次点击事件后使用全局变量存储名称,然后在对话框中使用它?

我在这里certificate了这个想法: http : //jsfiddle.net/NJa4U/

了解currentItem在该代码中的使用方式。