4 jquery
我正在阅读一本jQuery书,有时我看到的例子如下:
$('img[alt]').each(function(){
$(this).replaceWith('<span>' + $(this).attr('alt')+ '</span>')
}
Run Code Online (Sandbox Code Playgroud)
有时我会看到如下例子:
$('*').attr('title', function(index, value) {
return value + 'I am element ' + index + ' and my name is ' + this.id);
});
Run Code Online (Sandbox Code Playgroud)
所以有时看到它$(this)
,有时它只是this
有什么不同?我如何知道使用哪一个以及何时使用?
使用this
,如果你想直接访问多数民众赞成正在处理的DOM节点.它是任何jQuery注册的事件处理程序(即接收事件的元素)和许多其他jQuery函数的默认上下文.each
.
使用$(this)
如果你想调用该元素的jQuery的方法.
使用var $this = $(this)
如果你希望调用大量的元素,凡在我自己的编码风格"大量的",是"任何一个以上的" jQuery的方法.
在许多情况下,最好使用plain this
- 我考虑编写$(this).attr('id')
而不是this.id
反模式.
this
是DOM元素
$(this)
是jquery对象
所以用$(this)
你可以使用jQuery的像所有的方法attr()
,val()
...在那里,我们可以不this
..你必须使用this.value
或this.id
归档时间: |
|
查看次数: |
1907 次 |
最近记录: |