代码之家  ›  专栏  ›  技术社区  ›  Juho Vepsäläinen

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

  •  3
  • Juho Vepsäläinen  · 技术社区  · 16 年前

    下面的一些代码可以更好地说明这个问题。特别注意标有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 回复  |  直到 16 年前
        1
  •  3
  •   Zaqwsx    15 年前

    如果您使用的是eventhandlers,您可能希望使用event对象,而不是某些全局变量;)

    event.target就是你要找的。

    例如

    $('.sel').bind('dialogcreate', function(event, ui) {
    event.target.innerHTML = 'new content';
    });
    
        2
  •  5
  •   azatoth    16 年前

    或许以下内容更适合您的口味:

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

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

    post_values.exercise_name = 'foobar'; 具有

     post_values.exercise_name = $(this).data('exercise_name');
    
        3
  •  1
  •   Ryley    16 年前

    我想不出clicked事件和对话框之间是如何连接的,所以答案可能只是在每个click事件之后使用一个全局变量来存储名称,然后在对话框中使用它?

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

    currentItem 代码中使用了。