zwo*_*lin 12 javascript jquery dom
我用Google搜索并用谷歌搜索,我得出的结论是,我自己很难得到答案.
我正在尝试使用jquery或JavaScript来获取clicked元素的属性.我可以使用"this.hash"作为例子 - 它返回我认为的哈希值.
现在我想获得clicked元素类的名称.它甚至可能吗?怎么样?我在哪里可以找到这种信息?
jQuery文档? - 所有我能找到的方法和插件,没有属性..如果它在那里 - 请提供链接.
JavaScript文档? - 还有一个全面的吗?再请一个链接.
DOM文档? - W3C或其中的一个(链接赞赏).
什么是this.hash? - DOM JavaScript还是jQuery?
use*_*716 11
在jQuery中,如果您将click事件附加到所有<div>标记(例如),您可以像这样获取它的类:
示例: http ://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
Run Code Online (Sandbox Code Playgroud)
这使用jQuery的.click(fn)方法来分配处理程序,但是className直接从被单击的DOM元素访问该属性,该元素由表示this.
还有jQuery方法也可以这样做,比如.attr().
示例: http ://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Run Code Online (Sandbox Code Playgroud)
在这里,我用一个jQuery对象包装DOM元素,以便它可以使用jQuery提供的方法.这里的.attr()方法获取已设置的类.
Rob*_*ert 11
此示例将适用于页面中的每个元素.我建议使用console.log(event)Firebug/Developer工具将它转储到你的控制台中.
?$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});????
Run Code Online (Sandbox Code Playgroud)
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}?
Run Code Online (Sandbox Code Playgroud)
编辑
为了澄清,您不必e.srcElement.className为了拥有该类而记录控制台,希望这不会让任何人感到困惑.它意味着在函数中显示将具有类名.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
Run Code Online (Sandbox Code Playgroud)
这支持单击页面的任何位置.如果您单击的元素没有类名,则返回null或空字符串.
| 归档时间: |
|
| 查看次数: |
40269 次 |
| 最近记录: |