如果'这'in函数是一个特殊的类
If 'this' in function is a particular class
我有一个委托,当使用某些DOM元素的id或类点击它们时,它会被调用,并且我在函数中使用"this",但我该如何找出"this"实际上是哪个类或id?
这是我的代码:
$(document).delegate("#lg-menu li, #xs-menu li, .list-item", "click", function(e) {
a = $(this).attr("alpha");
b = $(this).attr("bravo");
c = $(this).attr("charlie");
d = parseInt($(this).attr("delta"));
}
this
是指触发事件的DOM对象,因此您可以使用DOM方法或jQuery方法来检查它或它的父对象:
$(document).delegate("#lg-menu li, #xs-menu li, .list-item", "click", function(e) {
var item = $(this);
// see which selector the item matches
if (item.is("#lg-menu li") {
// must be #lg-menu li
} else if (item.is("#xs-menu li") {
// must be #xs-menu li
} else {
// must be .list-item
}
}
.is()
为您完成了整个选择器评估。您还可以询问元素的各个属性,例如:
item.hasClass(".list-item") // does the item have a .list-item classname
item.parents("#lg-menu").length !== 0 // does the item have a #lg-menu parent
item.parents("#xs-menu").length !== 0 // does the item have a #xs-menu parent
this.tagName === "LI" // is the item an <li> tag
不过,如果你真的需要知道它是哪个项目,那么你可能只需要为每个项目使用单独的事件处理程序,并省去每次试图弄清楚它是哪个的工作。
$(document).delegate("#lg-menu li", "click", function(e) {
// code here
});
$(document).delegate("#xs-menu li", "click", function(e) {
// code here
});
$(document).delegate(".list-item", "click", function(e) {
// code here
});
要获得这个的id,可以读取像这样的dom元素的id属性
var id = this.id;
要检查它是否有特定的类,请使用类似的.hasClass()
var hasActive = $(this).hasClass('active')
您可以记录您的this
对象并找出它包含的字段:
$(document).delegate("#lg-menu li, #xs-menu li, .list-item", "click", function(e) {
console.log(this);
...
}
也可以使用bind(thisArg)
方法为函数手动设置this
此处描述
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- jQuery:循环一个具有不同超时值的循环
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 从javascript创建一个列表
- 节点导出返回一个空对象
- 使用clickToggle并在单击另一个元素时关闭元素
- 获取for in循环中对象的名称,用作另一个对象的键
- 使用一个菜单按钮添加animate-in和animate-out类
- CoffeeScript 在 'for v in values' 中创建一个全局变量 'v',导致事件中的错误引用
- 用车把.js做一个“if x in dict(json)”语句
- NodeJS put array in MongoDB doc.validate 不是一个函数
- 如何使第一个单选按钮在默认情况下选择一个列表中建立的for in循环使用trick
- 使word in变成一个链接jQuery
- For in循环只适用于对象中的最后一个键
- 有什么方法可以检测到一个drop-in braintree.js表单'
- TypeError: invalid 'in'在RequireJS模块中调用jQuery时,会出现一个错
- Javascript for…in + if-test(在一个表单内部的开关中)
- 我如何从一个方法内的for..in循环中获得多个返回
- 打印一个带有for/in循环的对象
- 如果'这'in函数是一个特殊的类