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

时间:2011-11-24 07:24:48

标签: javascript asp.net

我有一个动态添加图像按钮的页面,我希望它们在您点击它们时发送确认(删除)。

由于它们是动态的,我无法在.click事件中编写任何代码。

这是最好的方法吗?检查是真还是假,然后将其作为参数发送到代码后面的代码中的删除函数?或任何其他方式?

由于

4 个答案:

答案 0 :(得分:1)

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

检查imagebutton clientclick属性。

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

你的动态生成的imagebutton应该有点像这样: 为所有图像按钮创建commman事件hadler,并将这些imagebutton的id设置为主键值。

检查Respond to Button Web Server Control Events in Client Script 了解详情:

您可以创建自定义imagebutton usercontrol,它将在click事件中提供删除功能。在ItemRowCreated或GridView RowCreated事件上,将事件hadler分配给这些动态添加的控件。

如果它们不在任何数据绑定控件中,那么在运行时简单地指定那些属性。

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>");
        }

然后执行删除操作

答案 1 :(得分:0)

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

使用jQuery,只需使用:

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

答案 2 :(得分:0)

事件冒泡了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/

答案 3 :(得分:0)

在加载时“收集”触发.click和其他函数的对象,如果之后添加任何元素,则需要使用.delegate.bind来生成新元素也开了一个活动。

相关问题