如何"这个“;在jQuery中工作
How "this" works in jQuery
有人能解释一下"this"在jQuery中是如何工作的吗。我试着在网上找一些信息,但因为"this"在他通常的意思中用得很多,我找不到什么好的。
我希望能够在不给每个列表元素id的情况下更改列表元素(<li>
)的背景。
$('li').on('click.namespace', function() {
console.log(this); /* this is a reference to the DOM
element you clicked */
console.log($(this)); /* this is a jQuery reference to the
DOM element you clicked */
/* using jQuery reference you can change the background in this way */
$(this).css('background-image', 'url(...)');
});
$("li").click(function() {
$(this).css("background-color", "red");
});
下面是一个例子。$(this)
表示JQuery对象,this
表示单击的常规DOM对象。
您找到click()文档了吗?它显示了您应该如何使用单击处理程序,它甚至有使用$(this)
的示例。
这里有一个例子:
$('li').click(function() {
$(this).attr("class", "clicked");
});
当单击某个项目时,this
会获取所单击项目的值,即DOM元素。$(this)
允许您访问jquery API。
如果在li上设置onclick事件,则可以使用$(this)来获取li的jquery对象,然后添加一个类,例如$(this).addClass("newBackground").
<li>
。但是this
仍然是一个裸露的DOM元素,您需要用$()
包装它才能在它上使用jQuery方法
$('li').on('click', function() {
$(this).css({background:'red'});
});
有时您必须使用绑定函数(请参阅jQuery.proxy()
)作为事件处理程序,在这些情况下,您可以以不同的方式访问当前元素,而不是使用this
,您可以使用event.currentTarget
属性,请参阅http://api.jquery.com/event.currentTarget/
相关文章:
- PHP/AAJAX阻止jquery工作
- Chrome扩展和Chome浏览器中的Jquery工作方式不同
- 2次点击事件不会'我在jquery工作
- 使用 href=“#” JQuery 工作,但使用 href=“page.jsp” 不起作用
- 迭代 javascript 对象无法通过 jQuery 工作
- 让简单的Javascript / jQuery工作(Ariel Flesler的ScrollTo)
- 更新面板阻止 jquery 工作
- Jquery工作,但只是暂时的
- 一个jQuery工作,两个不工作
- 当我使用AngularJS部分时,如何让JQuery工作
- 为什么不;我的jquery工作(使用延迟、hasclass、addclass、removeclass、keyUp、key
- jQuery工作不正常
- 我有一个JQuery工作,但小越野车
- :has() jquery工作不正常
- JQuery工作得太快了
- 如果一个输入单选被选中,改变父元素'的颜色:不能'使它与jQuery工作
- Chrome扩展:访问DOM的弹出.html和让jQuery工作
- 如何使下拉jQuery工作
- 尝试使jquery工作
- RegEx不与我的jQuery工作