2010-05-28 137 views
3

我目前正在尝试挂接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" 
      ); 
     } 
    } 
}); 

下面是一些标记来显示代码如何与结构:

<div id="modify_exercise" class="dialog" title="{% trans 'Modify exercise' %}"> 
</div> 

<ul> 
    {% for exercise in exercises %} 
     <li> 
      <a class="exercise" href="#" title="{{ exercise.description }}"> 
       {{ exercise.name }} 
      </a> 
     </li> 
    {% endfor %} 
</ul> 

回答

3

更换post_values.exercise_name = 'foobar';如果你有工作的事件处理你可能想使用事件对象而不是一些全局变量;)

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

例如

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

啊,这看起来好像比我的好,假设它适合他需要如何使用它,为你赞扬。 – Ryley 2011-06-14 18:46:45

1

我想不出还有如何点击事件和对话框之间的连接,所以也许答案只是使用全局变量在每次点击事件后存储名称,然后在对话框中使用它?

我已经证明了这种想法在这里:http://jsfiddle.net/NJa4U/

了解如何currentItem在代码中使用。

+0

全局变量现在会做。谢谢。不过,如果一个对话框可以访问它的“父”元素(调用它的那个元素)会更好。 – 2010-05-28 16:55:20

5

也许以下可能适合自己口味的更好:

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

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

,并在按钮的回调,与

post_values.exercise_name = $(this).data('exercise_name'); 
相关问题