javascript - 脚本未在 Ajax 回发时执行

标签 javascript jquery asp.net ajax

我正在开发一个显示一些图 block 的网站。拼贴的高度可能会根据插入的图像和文本而变化。为了确保所有瓷砖达到相同的高度,我在 head 中编写了以下脚本:

function BindEvents()
{
    $(window).load(function () 
    {
        var maxHeight = Math.max.apply(null, $(".producttile").map(function () {
            return $(this).height();
        }).get());

        $('.producttile').height(maxHeight);

        maxHeight = Math.max.apply(null, $(".clistdiv").map(function () {
            return $(this).height();
        }).get());

        $('.clistdiv').height(maxHeight);
    });
}

上面的脚本已绑定(bind)到数据列表,如下所示:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <hr width="100%" noshade/>
        <script type="text/javascript">
            Sys.Application.add_load(BindEvents);
        </script>
        <asp:DataList 
                ID="DataList1"
                runat="server"
                onitemcommand="DataList1_ItemCommand1"
                class="itemsdatalist"
                RepeatDirection="Horizontal"
                RepeatLayout="Flow"
                onload="DataList1_Load">
            <ItemTemplate>
                ...........rest of the code

现在,当页面首次加载时,这种绑定(bind)和图 block 自动调整大小工作正常。按钮会触发 ajax 调用并引入更多图 block 并重新更新此更新面板。这就是问题所在。

不会再次调用BindEvents(),因此图 block 的大小不同,不会再次自动调整。

我尝试将脚本保留在更新面板内容模板中,希望它能够正常工作,但毫不奇怪,它根本不起作用。

请帮忙。

最佳答案

终于解决了这个问题。这是为您提供帮助的解决方案。 我刚刚在页面加载时编写了以下代码,并且效果完美。

protected void Page_Load(object sender, EventArgs e)
{
    if (((ScriptManager)this.Master.FindControl("ScriptManager1")).IsInAsyncPostBack)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<script language='javascript' type='text/javascript'>");
        sb.Append("Sys.Application.add_load(func);");
        sb.Append("function func() {");
        sb.Append("Sys.Application.remove_load(func);");
        sb.Append("var maxHeight = Math.max.apply(null, $('.producttile').map(function () { return $(this).height(); }).get()); $('.producttile').height(maxHeight);");
        sb.Append("maxHeight = Math.max.apply(null, $('.clistdiv').map(function () { return $(this).height(); }).get()); $('.clistdiv').height(maxHeight);");
        sb.Append("}");
        sb.Append("</script>");
        ScriptManager.RegisterStartupScript(this, GetType(), "script", sb.ToString(), false);
    }
}

感谢以下文章帮助我实现此解决方案: The solution link .

请告诉我这种方法是否存在安全/性能漏洞?

关于javascript - 脚本未在 Ajax 回发时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39177889/

相关文章:

javascript - 如何使用 CSS 和 JavaScript 更改标签的背景图像

javascript - 嵌套延迟在 YDN-DB 事务中

javascript - 如何使用 jQuery 替换跨度内的文本

javascript - jQuery getJSON 不发送 cookie

javascript - 单击时 2 个 div 之间的备用 z-index ?

c# - 在用户控件 asp.net C# 中公开 OnclientClick 函数

javascript - 从 contentEditable 中删除元素后出现奇怪的行为

c# - 如何在 web.config 文件中创建 <location> 标签?

asp.net - 无法从 MVC2 升级到 MVC3

php - 单击按钮时使用ajax获取文本框文本