Jquery对话框打开事件未触发

4

我有一个aspx页面,其中有两个具有相同类的面板,应该作为对话框功能。我尝试使用dialog("open")打开对话框,但似乎不起作用。 以下是代码片段。

<script type="text/javascript">
    $(document).ready(function() {

        $(".descPanel").dialog({ autoOpen: false,
            open: function() {
                $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").addClass("ui-state-error");
            }
        });

        $('.image').mouseover(function() {
            $($(this).parent()).children('.descPanel').dialog('open');
        });
    });
</script>

HTML结构:

<form id="form1" runat="server">
<div>
    <table>
        <tr id="tr">
            <td></td>
            <td></td>
            <td>
                <asp:Image runat="server" ImageUrl="~/Jquery/Untitled.jpg" CssClass="image" />
                <asp:Panel runat="server" ID="mypanel" CssClass="descPanel">
                    <asp:Label runat="server" ID="mylabel" CssClass="label" Text="hello"></asp:Label>
                </asp:Panel>
            </td>
        </tr>
    </table>
    <table>
        <tr id="tr">
            <td></td>
            <td></td>
            <td>
                <asp:Image ID="Image1" runat="server" ImageUrl="~/Jquery/Untitled.jpg" CssClass="image" />
                <asp:Panel runat="server" ID="Panel1" CssClass="descPanel">
                    <asp:Label runat="server" ID="Label1" CssClass="label" Text="hello1111"></asp:Label>
                </asp:Panel>
            </td>
        </tr>
    </table>
</div>
</form>

我已经验证了指向对话框的元素已经被正确引用。有没有解决方案让它正常工作?

2个回答

8

总体而言,您的代码应该像这样:

$('.image').each(function() {
  var panel = $(this).siblings('.descPanel');
  $(this).mouseover(function() {
    panel.dialog('open');
  });
});    
$(".descPanel").dialog({ 
    autoOpen: false,
    open: function() {
        $(this).siblings(".ui-dialog-titlebar").addClass("ui-state-error");
    }
});

您可以在此处测试

为什么?因为当您调用.dialog()时,它会将<div>包装在另一组元素中,但更重要的是它会移动这些元素到<body>的末尾,因此它们不再相对于原来的位置。在上面的代码中,我们正在查找与图像配对的面板并存储对它们的引用,它们被移动之前。

顺便说一下,您应该从代码中删除id="tr",重复的ID只会带来麻烦!(而且无效的HTML),在这种情况下,请使用类。


抱歉,Nick。我在提问时没有格式化好。它是ui-dialog-titlebar。我现在已经编辑了问题。此外,我无法在问题中添加完整的代码。它不被接受。 - Kunal
@Kunal - 啊,我看到你的错误了,你的问题需要更多的编辑才能显示HTML,稍等一下。 - Nick Craver
Nick,你能帮我格式化一下问题吗?我的完整问题看起来不是那样的。提前感谢你。 - Kunal
@Kunal - 是的,已经完成了,并更新了回答以匹配您在此处实际遇到的问题,查看所有代码后很明显 :) - Nick Craver
非常感谢。首先,我在我的代码中使用了asp:repeater,因此它会重复HTML,因此tr获取相同的ID。非常感谢您的快速回复。您能告诉我为什么要使用each函数吗?我不想循环遍历所有图像。我只想打开鼠标悬停在其上的图像的对话框。 - Kunal
明白了,非常感谢 :)。我已经完全理解了。太棒了!:) - Kunal

5

刚发现您也可以通过以下方式将函数绑定到 open 事件:

yourDialog.bind("dialogopen", function(event, ui) {
    //your code here
});

这正是我所需要的,全局监听对话框创建。干杯 :) - Sophistifunk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接