判断是否点击指定按钮

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm7.aspx.cs" Inherits="WebApplication10.WebForm7" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="submit" class="button" value="搜索" name="search" />
     <input class="button" id="Button1" type="submit" name="delete" onclick="" value="删除" />             
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;

namespace WebApplication10
{
    public partial class WebForm7 : System.Web.UI.Page
    {
        private NameValueCollection m_ModifiedForms = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsClick("search"))
            {
                Response.Write("Search");
            }

            if (IsClick("delete"))
            {
                Response.Write("Delete");
            }
        }


        /// <summary>
        /// 判断是否点击了指定名称的按钮
        /// </summary>
        /// <param name="buttonName"></param>
        /// <returns></returns>
        public bool IsClick(string buttonName)
        {
            if (GetForm(buttonName) != null || (GetForm(buttonName + ".x") != null && GetForm(buttonName + ".y") != null))
                return true;
            else
                return false;
        }

        internal string GetForm(string key)
        {
            if (m_ModifiedForms == null)
                return Request.Form[key];
            else
                return m_ModifiedForms[key];
        }
    }
}


### 判断点击的元素是否指定元素 为了验证用户点击的具体DOM元素,通常会利用事件对象中的`target`属性来获取触发该事件的实际元素。一旦捕获到这个目标元素,就可以通过比较其特性(比如ID或者类名)与预期的目标进行匹配。 如果希望确认点击的是特定类型的按钮或其他HTML标签,则可以通过检查节点名称(NodeName)来进行对比: ```javascript document.addEventListener('click', function(event){ if (event.target.nodeName === 'BUTTON') { console.log("Clicked element is a button"); } }); ``` 对于更精确的选择器,例如基于某个唯一的ID或自定义的数据属性(data attribute),可以采用如下方式实现更为严格的校验逻辑[^2]: ```javascript // 假设要检测id="myButton" 的<button>元素被点击 document.addEventListener('click', function(event){ let targetElement = event.target; // 使用matches方法判断是否符合选择条件 if(targetElement.matches('#myButton')){ alert('The specified button has been clicked!'); }else{ console.log('Another element was clicked'); } }, false); ``` 需要注意的是,在某些情况下可能需要阻止冒泡行为以防止不必要的父级监听器响应相同的事件。这可以通过调用 `Event.stopPropagation()` 方法完成[^1]。 另外,当函数内部操作依赖于外部创建的对象时,应当考虑将此对象作为参数传递给函数而不是直接访问全局作用域内的变量,以此保持良好的编程实践并减少潜在错误的发生几率[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值