javascript 动态获取控件ID - JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7178309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:13:07  来源:igfitidea点击:

Get the control ID dynamically - JQuery

javascriptjqueryasp.net

提问by SRA

How can I get the control ID of a asp.net control while mouseover on a control dynamically. For example, I've page called "Default.aspx" which has 5 text boxes, two check boxes, 2 radio buttons. So, when I mouseover a specific control I should be able to get the currently hovered controls ID using javascript or jquery. I dont want to write code for every control, instead the javascript should be able to detect the mouseover event when the mouse is moved over any control and in the backend the controld ID should be returned.

如何在鼠标悬停在控件上时动态获取 asp.net 控件的控件 ID。例如,我有一个名为“Default.aspx”的页面,它有 5 个文本框、两个复选框和 2 个单选按钮。因此,当我将鼠标悬停在特定控件上时,我应该能够使用 javascript 或 jquery 获取当前悬停的控件 ID。我不想为每个控件编写代码,相反,当鼠标移到任何控件上时,javascript 应该能够检测到 mouseover 事件,并且在后端应该返回受控 ID。

Any solution ?

任何解决方案?

回答by Rafay

$("input").mouseenter(function(e){
e.stopPropagation();
$id=$(this).attr("id");
});

this will return the idof input control currently being hovered

这将返回id当前悬停的输入控件

回答by jfriend00

I chuckle a bit when jQuery developers use jQuery in their handler function when it's the long way to get the answer. Here's a shorter/faster way:

当 jQuery 开发人员在他们的处理程序函数中使用 jQuery 时,我有点笑了,因为这是获得答案的漫长道路。这是一种更短/更快的方法:

$("input").mouseenter(function(e){
    var id = this.id;
    // do whatever you want with the id here
});

If you're truly trying to pass this to your back-end web server (a part of your question that was not clear to me), then you will need to initiate communications to the web server either using a posted form or an ajax call.

如果你真的想把它传递给你的后端 web 服务器(你的问题的一部分,我不清楚),那么你将需要使用发布的表单或 ajax 调用启动与 web 服务器的通信.

回答by cgcarter1

This might not be the best practices way, but I would set the onmouseover event to trigger a function that sets the value of a hidden field. In your JQuery read the value of that field and you will know which one they did the mouseover on...

这可能不是最佳实践方式,但我会设置 onmouseover 事件来触发设置隐藏字段值的函数。在您的 JQuery 中读取该字段的值,您将知道他们将鼠标悬停在哪个...

回答by Chris

$("input").hover(function(){
    // hover on
    var theId = $(this).attr("id");
    if(theId) {
        // do something 
    }
    else {
        // no id found  
    }
},
function(){
    // hover off
});

I suppose you won't need to check if an id exists since it's a .NET control though

我想你不需要检查 id 是否存在,因为它是一个 .NET 控件