使用jQuery确定单击了哪个元素id或类
Identify which element id or class was clicked using jQuery?
假设我有
<body>
<div id="stuff">
<div id="cat">a</div>
<div id="dog">b</div>
<div id="elephant">c</div>
<div id="rabbit">d</div>
<div id="frog">e</div>
</div>
</body>
到目前为止,我能得到的壁橱是与JS,
document.getElement('body').onclick = function(e){
alert(e.target.innerHTML);
}
当我想要像"猫"或"狗"这样的文字div id而不是"a"或"b"时,它打印出div的内容。我也在尝试使用jQuery来完成这个,我在正确的方向吗?
为了使用jQuery方法,你需要包含jQuery js文件。
与jQuery$('body').click(function(e){
alert(e.target.innerHTML);
alert(e.target.id)
alert($(e.target).attr('id'));
});
使用Javascript document.getElement('body').onclick = function(e){
alert(e.target.innerHTML);
alert(e.target.id)
}
使用JQuery的html页面示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
document.getElement('body').onclick = function(e){
alert(e.target.innerHTML);
alert(e.target.id)
}
</script>
</body>
</html>
http://jsbin.com/ohotuv/1/edit
document.getElementById('stuff').onclick = function( e ){
alert( e.target.id );
};
金桥道:
$('#stuff').click(function( e ){
alert( e.target.id );
});
如果它没有ID,但是有CLASS(并且你想要它!),你可以这样做:
http://jsbin.com/ohotuv/3/edit -(其中"elephant"是一个类)
$('#stuff').click(function( e ){
var name = e.target.id || e.target.className;
alert(name);
});
如果您使用纯javascript
,您可能需要使其跨浏览器兼容。
window.onload=function(){
document.getElementsByTagName('body')[0].onclick = function(e){
e = e ? e : window.event;
var source = e.target || e.srcElement;
alert(source.id);
}
}
我建议阅读一下jQuery.on()。
在你的例子中,我建议:
$("body").on("click", function(event){
alert($(this).id);
});
尽管强烈建议减少作用域,但您要查找的是单击事件中的哪些元素。例如:
$("#stuff").on("click", "div", function(event){
alert($(this).id);
});
这将只处理任何div元素内的html标签的东西的id。减少处理事件的上下文有助于封装和调试问题。
相关文章:
- 选择不带选择器的元素,仅使用元素ID
- 从元素id中获取值,而不是从javascript中的名称中获取值
- 如何将第二个元素id注入到网站元素中
- 将 JavaScript 元素 ID 传递给 PHP 或 Form Variable
- 如何在 javascript 中将表单中的元素 id 值作为数组传递
- 用于指定元素 ID 的正确 JavaScript 语法是什么
- 如何从 jQuery 中的 ajax 函数中的类访问元素 ID
- JavaScript获取多个已知元素ID
- 使用ng repeat时元素ID重复
- 在使用onblur进行输入评估时,是否可以获得单击对象的元素id
- JQuery通过变量标识元素id:多个表行
- 当元素ID包含美元符号时,Javascript中的getElementByid.当ID包含美元符号时,
- 我得到未捕获的类型错误:无法读取属性'选项'即使定义了元素id,也为null
- 元素id未被接受为函数参数
- 使用jquery获取类元素id
- 如何在没有任何元素id的情况下检索表中的文本内容
- jquery按类确定元素id
- 获取元素ID并传递到函数中
- 使用jquery获取元素id
- JavaScript文档.getElementById(“id”)和元素id属性