在jQuery对话框中获取底层元素

时间:2015-04-17 14:15:26

标签: javascript jquery jquery-ui

我想将jQuery对话框附加到它的当前父级(让我们说,因为它包含输入,而它的父级是表单中的子级)。 所以问题在这里说明:

http://jsfiddle.net/pprrm4st/2/

我绝对需要找到当前元素的.container并将对话框附加到它。

appendTo: $(this).closest('.container'), //I thougnt $(this) would be current .element

否则有办法告诉jQuery不要移动.element吗?

2 个答案:

答案 0 :(得分:2)

this不是该范围内的元素,您应该注意,没有函数调用可以设置this值。

以下是使用each循环解决问题的方法,其中this将是元素等。

$(".element").each(function() {
    $(this).dialog({
        modal: true,
        autoOpen: false,
        appendTo: $(this).closest('.container'),
        buttons: {
            "I've read and understand this": function() {
                $(this).dialog("close");
            }
        }
    });
});

$('a').click(function(){
    $(".element").dialog('open');
});

FIDDLE

答案 1 :(得分:0)

如果您不想要循环,这也可以解决问题:

$(".element").dialog({
    modal: true,
    autoOpen: false,
    buttons: {
        "I've read and understand this": function() {
            $(this).dialog("close");
        }
    }
}).dialog( "option", "appendTo", $(".element").closest('.container') );

$('a').click(function(){
    $(".element").dialog('open');
});

甚至更短(并且更便宜,因为只有在DOM寻找.element时才会遍历):

var elem = $(".element")

elem.dialog({
    modal: true,
    appendTo: elem.closest('.container'),
    autoOpen: false,
    buttons: {
        "I've read and understand this": function() {
            $(this).dialog("close");
        }
    }
})

$('a').click(function(){
    elem.dialog('open');
});
相关问题