JavaScript中的按钮事件未触发

3
我已经为一个特定的设备添加了一个jQuery模态弹出窗口来保存上传文件。模态窗口弹出,取消按钮可以正常工作,但是我无法弄清楚如何让保存按钮触发onclick事件...
这是我所做的:
     $(function () {
        $("#dialogCustUploads").dialog("destroy");
        $("#dialogCustUploads").dialog({
            title: "Upload Files",
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 'auto',
            buttons: {
                Save: function () {
                    $(document.getElementById('<%=btnSave.ClientID %>')).click();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    });

    function showCustUploads() {
        $(function () {
            $("#dialogCustUploads").dialog("open");
                    });
        $(".dialogCustUploads").parent().appendTo($("form:first"));  
    }


    <div id="dialogCustUploads" style="display: none">     
    <table style="width:100%;">
                <tr>
                    <td class="auto-style1">
                        <asp:Label ID="Label16" runat="server" Text="Client"></asp:Label>

                    </td>
                    <td>
                        <asp:Label ID="lblClientUploadName" runat="server"></asp:Label>
                    </td>
                </tr>
                    <tr>
                <td>
                    <asp:Label ID="Label19" runat="server" Text="Certificate no" ></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtCertificateNo" runat="server" Width="410px"></asp:TextBox>
                </td>
            </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label14" runat="server" Text="Upload Option"></asp:Label>
                    </td>
                    <td>
                        <asp:DropDownList ID="lstUploadOption" runat="server" AppendDataBoundItems="True" Width="410px"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1">
                        <asp:Label ID="Label18" runat="server" Text="File"></asp:Label>
                    </td>
                    <td>
                        <asp:FileUpload ID="fuPath" runat="server" Width="408px" />
                        <br />
                        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1"></td>
                    <td>
                        <asp:Button ID="btnSave" style="display: none;" runat="server" Text="Save" OnClientClick="btnSave_Click"  BackColor="White" />                          
                    </td>
                </tr>
            </table>
</div>

我不确定我错过了什么或做错了什么...这是我第一次使用JavaScript...任何帮助都将不胜感激!保存按钮没有任何反应...
编辑
感谢大家的帮助!我已更新按钮以删除内联样式:
    <asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="btnSave_Click" ClientIDMode="Static" /> 

我尝试使用您给我的以下内容:
    1. $("#<%=btnSave.ClientID%>").click();
    2. document.getElementById('<%=btnSave.ClientID %>').click();
    3. <asp:Button ID="btnSave" style="display: none;" runat="server" Text="Save" OnClientClick="btnSave_Click" ClientIDMode="Static"  BackColor="White" /> 
     document.getElementById('btnSave').click();
    4. $('<%=btnSave.ClientID %>').trigger("click");

但它们都会给我一个错误消息,内容如下:
    Microsoft JScript runtime error: 'btnSave_Click' is undefined

当表单出现问题时,按钮显示为以下内容:
    <input type="submit" name="ctl00$MainContent$btnSave" value="Save" onclick="btnSave_Click;" id="btnSave" /> 

我正在做的事情还有什么问题吗?

编辑

这是我的源代码:

    <script type="text/javascript">
    $(function () {
        $("#dialog").dialog("destroy");
        $("#dialog").dialog({
            title: "Message",
            autoOpen: false,
            modal: true,
            buttons: {
                Ok: function () {
                    $(this).dialog("close");
                }
            }
        });
    });
    function showMessage() {
        $(function () {
            $("#dialog").dialog("open");
        });
        return false;
    }

    $(function () {
        $("#dialogCustUploads").dialog("destroy");
        $("#dialogCustUploads").dialog({
            title: "Upload Files",
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 'auto',
            buttons: {
                Save: function () {
                    document.getElementById('<%=btnSave.ClientID %>').click();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    });

    function showCustUploads() {
        $(function () {
            $("#dialogCustUploads").dialog("open");
                    });
        $(".dialogCustUploads").parent().appendTo($("form:first"));  
    }

</script>

我的div用于按钮点击事件:

    <div id="dialogCustUploads" style="display: none">     
    <table style="width:100%;">
                <tr>
                    <td class="auto-style1">
                        <asp:Label ID="Label16" runat="server" Text="Client"></asp:Label>

                    </td>
                    <td>
                        <asp:Label ID="lblClientUploadName" runat="server"></asp:Label>
                    </td>
                </tr>
                    <tr>
                <td>
                    <asp:Label ID="Label19" runat="server" Text="Certificate no" ></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtCertificateNo" runat="server" Width="410px"></asp:TextBox>
                </td>
            </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label14" runat="server" Text="Upload Option"></asp:Label>
                    </td>
                    <td>
                        <asp:DropDownList ID="lstUploadOption" runat="server" AppendDataBoundItems="True" Width="410px"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1">
                        <asp:Label ID="Label18" runat="server" Text="File"></asp:Label>
                    </td>
                    <td>
                        <asp:FileUpload ID="fuPath" runat="server" Width="408px" />
                        <br />
                        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1"></td>
                    <td>
                        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" /> 

                    </td>
                </tr>
            </table>
</div>

我从一个gridview的点击事件中调用模态弹出窗口:

    <asp:GridView ID="gvDeviceCalibration" runat="server" CellPadding="10" Width="90%" AutoGenerateColumns="False"  BorderWidth="1px">
                            <HeaderStyle BackColor="#3A4F63" BorderWidth="1px" Font-Size="7pt" Wrap="False" ForeColor="White" />
                            <RowStyle BackColor="White" Wrap="True" />
                                <AlternatingRowStyle BackColor="#FFCC99" Wrap="True" />
                            <Columns>
                                <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" ></asp:BoundField>
                                <asp:BoundField DataField="InstrumentType" HeaderText="Instrument Type" ReadOnly="True" SortExpression="InstrumentType"> <HeaderStyle Wrap="True" /></asp:BoundField>

                                <asp:BoundField DataField="Make" HeaderText="Make" ReadOnly="True" SortExpression="Make"> 
                                    <HeaderStyle Wrap="True" />
                                </asp:BoundField>
                                <asp:BoundField DataField="Location" HeaderText="Location" ReadOnly="True" SortExpression="Location"></asp:BoundField>
                                <asp:BoundField DataField="SubLocation" HeaderText="Sub Location" ReadOnly="True" SortExpression="Sub Location"> <HeaderStyle Wrap="True" /></asp:BoundField>
                                <asp:BoundField DataField="CalibrationIntervals" HeaderText="Calibration Intervals" ReadOnly="True" SortExpression="CalibrationIntervals"> <HeaderStyle Wrap="True" /></asp:BoundField>
                                <asp:BoundField DataField="SerialNo" HeaderText="Serial No" ReadOnly="True" SortExpression="SerialNo"> <HeaderStyle Wrap="True" /></asp:BoundField>
                                <asp:BoundField DataField="WorkingRange" HeaderText="Working Range" ReadOnly="True" SortExpression="WorkingRange"> <HeaderStyle Wrap="True" /></asp:BoundField>
                                <asp:BoundField DataField="Classification" HeaderText="Classification" ReadOnly="True" SortExpression="Classification"></asp:BoundField>
                                <asp:BoundField DataField="CalibrationDate" HeaderText="Calibration Date" DataFormatString="{0:yyyy/MM/dd}" ReadOnly="True" SortExpression="CalibrationDate">                                        
                                 <HeaderStyle Wrap="True" />
                                </asp:BoundField>
                                <asp:BoundField DataField="CalibrationHouse" HeaderText="Calibration House" ReadOnly="True" SortExpression="CalibrationHouse"><HeaderStyle Wrap="True" /></asp:BoundField>
                                <asp:BoundField DataField="Owner1s" HeaderText="Owner 1" ReadOnly="True" SortExpression="Owner1s"></asp:BoundField>
                                <asp:BoundField DataField="Owners2" HeaderText="Owner 2" ReadOnly="True" SortExpression="Owners2"></asp:BoundField>
                                <asp:BoundField DataField="CreatedBy" HeaderText="Created By" ReadOnly="True" SortExpression="CreatedBy"></asp:BoundField>
                                <asp:TemplateField HeaderText="Select">
                                    <ItemTemplate>
                                        <asp:ImageButton ID="UpdateStatus" runat="server" Height="22" BorderStyle="None" BackColor="Transparent"
                                            ImageUrl="~/Images/Sign-Select-icon.png" OnClick="SelectCalDevice_Click"  Width="22"  /><%-- --%>

                                    </ItemTemplate>
                                </asp:TemplateField>                                   
                                <asp:TemplateField HeaderText="Upload">
                                    <ItemTemplate>
                                        <asp:ImageButton ID="CustUploadFiles" runat="server" Height="22" BorderStyle="None" BackColor="Transparent"
                                            ImageUrl="~/Images/UploadFilesTrans.png" OnClick="SelectCustFiles_Click" Width="22"  /> 
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="View ">
                                    <ItemTemplate>
                                        <asp:ImageButton ID="CustViewFiles" runat="server" Height="25" BorderStyle="None" BackColor="Transparent"
                                            ImageUrl="~/Images/msgicon.png" ForeColor="Transparent"  Width="25" OnClick="ViewCustFiles_Click"  />
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <EmptyDataTemplate>                                
                                <HeaderTemplate>There are no leads listed.</HeaderTemplate>
                            </EmptyDataTemplate> 
                        </asp:GridView>

这是SelectCustFiles_Click函数,我在这里显示弹出窗口:

    protected void SelectCustFiles_Click(object sender, EventArgs e)
    {
        ImageButton lb = sender as ImageButton;
        GridViewRow row = (GridViewRow)lb.NamingContainer;
        txtRowID.Text = row.Cells[0].Text;
        lblClientUploadName.Text = row.Cells[1].Text;

        PopulateUploadOptions();
        //modalCustUploads.Show();
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "popUpMessage", "showCustUploads();", true);
    }

我将尝试从脚本中调用的点击事件如下:

    protected void btnSave_Click(object sender, EventArgs e)
    {
        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (fuPath.HasFile)
        {
            // Get the size in bytes of the file to upload.
            int fileSize = fuPath.PostedFile.ContentLength;

            // Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
            if (fileSize < 45497717)
            {
                // Call a helper method routine to save the file.
                //SaveFile(fuPath.PostedFile);
                SaveFile();
                fuPath.Dispose();

                lbljQMessage.Text = "Update successful";
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "popUpMessage", "showCustUploads();", true);
                //modalCustUploads.Show();
            }
            else
                lblMessage.Text = "You did not specify a file to upload.";
        }
    }

我收到一个“btnSave未定义”的错误...
这是我正在使用的脚本:
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
   <script src="../Scripts/jquery-ui-1.8.17.custom.min.js" type="text/javascript"></script>

我找到了问题所在...我将对话框附加在了错误的位置。正确的做法应该是:
     function showCustUploads() {
        $(function () {
            $("#dialogCustUploads").dialog("open");
                    });
        $(".dialogCustUploads").parent().appendTo($("form:first"));  
    }

这应该是:

     function showCustUploads() {
        $(function () {
            $("#dialogCustUploads").dialog("open");
                    }); 
    }

而不是这样:

     $(function () {
        $("#dialogCustUploads").dialog("destroy");
         $("#dialogCustUploads").dialog({
            title: "Upload Files",
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 'auto',
            buttons: {
                Save: function () {
                  //  __doPostBack("<%=btnSave.UniqueID %>", "");
                    $($get("<%=btnSave.UniqueID %>")).click();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    });

应该是这样的:

     $(function () {
        $("#dialogCustUploads").dialog("destroy");
        var dlgUploads = $("#dialogCustUploads").dialog({
            title: "Upload Files",
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 'auto',
            buttons: {
                Save: function () {
                  //  __doPostBack("<%=btnSave.UniqueID %>", "");
                    $($get("<%=btnSave.UniqueID %>")).click();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
        dlgUploads.parent().appendTo(jQuery("form:first"));
    });

感谢大家的帮助!!!非常感激!


请仅使用jQuery或JavaScript,jQuery语法为$('#<%=btnSave.ClientID %>')).click(); - bitkot
@user2042152:您是否同意使用简单的“浏览器确认弹出窗口”而不是使用“jQuery模态弹出窗口”来询问保存文件的确认?如果是这种情况,我有一个建议。请告诉我。 - user3240361
@user3240361,是的,我是...以前我使用过Ajax控件工具包,但由于许多兼容性问题,我不得不寻找其他东西,只要它与IE 8兼容即可... - Kerieks
@user2042152:请查看我下面的答案。 - user3240361
9个回答

5
 document.getElementById('<%=btnSave.ClientID %>').click();

 Or

 $('#<%=btnSave.ClientID %>').click();

嗨,感谢您的帮助,这触发了事件,但是它给我一个“Microsoft JScript运行时错误:'btnSave_Click'未定义”的错误? - Kerieks
从按钮中移除OnClientClick。在脚本中添加$('<%=btnSave.ClientID %>').trigger("click");。 - RGS
通过移除onclientclick并添加上述方法,按钮似乎没有任何反应... - Kerieks

3
$('#<%=btnSave.ClientID %>').trigger("click"); // Make sure you use '#' as part of your jQuery selector

假设$('<%=btnSave.ClientID %>')指代按钮,你可以通过检查$('<%=btnSave.ClientID %>').length == 1来确认。


谢谢,它给了我一个错误提示:"Microsoft JScript运行时错误:'btnSave_Click'未定义"。 - Kerieks
当调用alert($('<%=btnSave.ClientID %>').length)时,会得到什么?另外,你使用的是哪个版本的jQuery? - user3455395
长度返回为0,我正在使用以下2个脚本:<script src="../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="../Scripts/jquery-ui-1.8.17.custom.min.js" type="text/javascript"></script> - Kerieks
你只需要一个,我会选择第二个。我最好的建议是使用Chrome开发工具 - 在Chrome中,只需右键单击按钮,然后在上下文菜单中选择“检查元素”。检查其中的按钮并将其与<%=btnSave.ClientID%>进行比较,它们必须相同。 - user3455395
抱歉,必须使用$("#" + Id)。如果你硬编码为$('#btnSave'),它会起作用吗? - user3455395
显示剩余2条评论

3
尝试仅使用以下代码: $("#<%=btnSave.ClientID%>").click();
并删除按钮的内联样式。

我已经删除了内联样式,但是它给出了一个错误:“Microsoft JScript运行时错误:'btnSave_Click'未定义”。 - Kerieks
尝试使用OnClick替换OnClientClick。 - Dhaval Javiya
它仍然没有做任何事情,我尝试使用:__doPostBack('btnSave','OnClick'); 它关闭了对话框...但仍然无法触发点击事件.... - Kerieks
你能分享一下你的服务器端和客户端代码以便更好地理解吗? - Dhaval Javiya

3

你做错了:

$(document.getElementById('<%=btnSave.ClientID %>')).click();

您混淆了jQuery和JavaScript选择器,您应该使用jQuery的方式:

$('#<%=btnSave.ClientID %>').click();

或者使用原生JavaScript实现:

document.getElementById('<%=btnSave.ClientID %>').click();

注意:您可以将属性设置为Static,然后也可以这样做:

<asp:Button ID="btnSave" style="display: none;" runat="server" Text="Save" OnClientClick="btnSave_Click" ClientIDMode="Static"  BackColor="White" /> 

而在jQuery中:

$('#btnSave').click();

或者在javascript中:
document.getElementById('btnSave').click();

嗨,感谢您的帮助,现在点击保存按钮会出现错误:“Microsoft JScript运行时错误:'btnSave_Click'未定义”...有什么想法吗? - Kerieks
您所提供的按钮 OnClientClick 事件未定义,请移除该事件或添加 btnSave_Click 的定义。 - Ehsan Sajjad
谢谢,我明白了如何得到一个回调。但是它会在到达保存方法之前进行完整的回调,清除数据吗? - Kerieks

2

IT应该是

document.getElementById('<%=btnSave.ClientID %>').click();

替代
$(document.getElementById('<%=btnSave.ClientID %>')).click();

因为你正在使用JavaScript,顺带一提jQuery也是JavaScript,但使用$()将创建jQuery对象,你正在混合使用两者。

2

OnClientClick 指定要执行的客户端 JavaScript 函数,但看起来您正在尝试使用它来执行服务器端方法。 OnClick 将执行服务器端方法:

OnClick="btnSave_Click"

当我移除OnClientClick并添加Click事件时,什么也没有发生,按钮没有回传任何东西...我可以点击按钮多次,但什么也没有发生... - Kerieks

1
尝试只使用 < /p>。
   $("#btnSave").click();

1

试试这个

$('<%=btnSave.ClientID %>').click();

1
如果您想要实现以下内容:
  1. 当用户在GridView(gvDeviceCalibration)中单击“上传图像”按钮时,会显示jQuery模态窗口(或弹出窗口)。

  2. 如果用户单击“取消”,则不执行任何操作;否则,如果用户单击“保存”按钮,则转到Code behind事件处理程序“btnSave_Click”。

可能的解决方案(将“gvDeviceCalibration” GridView中的“Upload”模板字段更改为以下内容):
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
    <asp:ImageButton ID="CustUploadFiles" runat="server" Height="22" BorderStyle="None" BackColor="Transparent" ImageUrl="~/Images/UploadFilesTrans.png" OnClick="btnSave_Click" Width="22" OnClientClick="return confirm('Are you sure you want to Save?')"  /> 
</ItemTemplate>
</asp:TemplateField>

在上面的代码中,我们使图像按钮通过“OnClientClik”事件进行确认并通过“OnClick”事件调用保存方法的代码后台调用。
在这种情况下,您不需要使用“SelectCustFiles_Click”方法或“jquery modal”。
如有任何问题,请告诉我。

谢谢您的建议!这个方法可以行得通,但是我有一个证书号码和上传日期,用户可能会先选择上传再输入其他数据,如果我禁用了其他数据的上传选项,那么这样做就不太友好了... 你有什么其他想法吗? - Kerieks
@user2042152:我没太明白这部分内容!你能再解释一下吗? - user3240361
1
我需要保存证书编号,以及证书应该完成的日期和上传的文件。在上传控件的onclick事件中进行操作会使用户体验变得复杂...我不能将保存方法从上传控件中提取出来,因为这要求在保存这些字段之前必须完成并验证其他两个字段。 - Kerieks

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