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

Juh*_*nen 3 javascript jquery 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"
            );
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

aza*_*oth 5

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

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

$("#modify_exercise").data('exercise_name',$(this).text());
Run Code Online (Sandbox Code Playgroud)

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

 post_values.exercise_name = $(this).data('exercise_name');
Run Code Online (Sandbox Code Playgroud)