Javascript确认没有代码在代码后面

Javascript confirm without code in code behind

本文关键字:代码 确认 Javascript      更新时间:2023-09-26

我有一个页面动态添加的imagebuttons,我希望他们发送一个确认当你点击他们(删除)。

因为它们是动态的,所以我不能在。click事件中编写任何代码。

最好的方法是什么?检查是否为真或假,然后将其发送到代码中的删除函数与控件作为参数?或者其他方式?

谢谢

如果您希望能够取消提交,请将OnClientClick属性设置为字符串"Return"和函数名。然后客户端脚本可以通过返回false来取消提交。

检查imagebutton clientclick属性。

void Button1_Click(Object sender, EventArgs e)
        Label1.Text = "Server click handler called.";
    End Sub

你的动态生成的imagebutton应该像这样:为所有imagebutton创建命令事件处理程序,并将这些imagebutton的id设置为主键值。

检查响应按钮Web服务器控制事件在客户端脚本中的详细信息:

您可以创建一个自定义imagebutton用户控件,它将在单击事件时提供删除功能。在ItemRowCreated或GridView RowCreated事件中,为这些动态添加的控件分配事件处理程序。

如果它们不在任何数据绑定控制中,则在运行时简单地分配它们的属性。

protected void Page_Init(object sender, EventArgs e)
    {
        ImageButton btn = new ImageButton();
        btn.ID = "1";
        btn.ImageUrl = "http://icons.iconarchive.com/icons/deleket/button/256/Button-Fast-Forward-icon.png";
        btn.OnClientClick = "return confirm('Ready to submit.')";
        btn.Click += new ImageClickEventHandler(btn_Click);
        this.form1.Controls.Add(btn);
    }

检查事件处理程序中的控件id。

private void btn_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            Response.Write("<script>alert('Image button with id = " + btn.ID + "clicked');</script>");
        }

然后执行删除操作

使用jQuery (javascript框架)很容易做到,即使想使用纯javascript,您也需要为所有的删除图像按钮添加一个类并为其添加处理程序

使用jQuery,只需使用这个:

$(".deleteImageButton").bind("click", function() {
   var res = confirm("Are you sure you want to delete?");
   return res;
});

触发.click和其他函数的对象在加载时被"收集",如果在此之后添加任何元素,您需要使用.delegate.bind来使新元素也触发事件

事件冒泡DOM,即:它们将被它所发生的元素触发,以及它的所有父元素(直到文档节点本身)。这样可以很容易地解决问题:只需将单击处理程序附加到按钮的容器上。jQuery通过委托函数让它变得更容易,下面是一些示例代码:

$('#buttons').delegate('.delete_control', 'click', function(e) {
    e.preventDefault();
    e.stopPropagation(); // maybe you don't need these 2, you can remove them if so
    if (confirm('Are you sure you want to delete that element?')) {
        // make an ajax request to delete the image. alternatively you can submit
        // a hidden form, with the controlid in an input, but this is way simpler.
        $.post('/url/to/delete/control/by/id/' + e.target.id, function() {
            $(e.target).remove(); // to delete the button when the request is done.
        });
    }
});

这里是一个JSFiddle页面,显示了整个工作:http://jsfiddle.net/8d7D4/