2012-10-16 51 views
3

我只是想清理一些jQuery,并不能完全弄清楚调用什么是将jQuery调用范围限制到特定的dom元素。举一个例子,我有以下代码:范围到DOM元素

$('#outer-element .first-class').html('wanna'); 
$('#outer-element .second-class').html('scope'); 
$('#outer-element .third-class').html('better'); 

我猜测调用每个那些第一/第二/第三级呼叫的一个共同的外元件呼叫的是一个更好的方法,我只是不确定语法是怎么做的。我猜根据

$('#outer-element').SOMETHINGGOESHERE(function() { 
    $(this).find('.first-class').html('wanna'); 
    $(this).find('.second-class').html('scope'); 
    $(this).find('.third-class').html('better'); 
}); 

任何想法?比我上面建议的更优雅吗?总之 - 我知道上面是丑陋的。我正在寻找这样的JavaScript更漂亮的方法。

回答

4

存储对象中的变量,并发现它缓存的对象

var $this = $('#outer-element'); 

    $this.find('.first-class').html('wanna'); 
    $this.find('.second-class').html('scope'); 
    $this.find('.third-class').html('better'); 
5

只要代码量是可控的,我平时一起穿插.end()电话连锁一切:

$('#outer-element') 
    .find('.first-class').html('wanna').end() 
    .find('.second-class').html('scope').end() 
    .find('.third-class').html('better').end(); 

如果你这样做事,你必须要超小心包含每个只有一个.end()遍历操作;对于这个原因,它可能是一个好主意,通过在Python的提醒方式使用空格超越职责要求:

$('#outer-element') 
    .find('.first-class') 
     .html('wanna') 
    .end() 
    .find('.second-class') 
     .html('scope') 
    .end() 
    .find('.third-class') 
     .html('better') 
    .end(); 

最后.end()是没有必要的,但它可能是在未来,如果代码被修改。比对不起更安全。

+0

只是想知道里面。有没有理由在其他2个答案中使用这种方法? – Dcullen

+1

@Dcullen:输入稍微少一些,这是一个偏好的事情。没有技术原因。 – Jon

+1

@Dcullen有些人更喜欢这种方法,因为它变成了一个班轮。在现代浏览器中,原始代码可能比使用'.find'更有效率,而不是它们之间的显着差异。 –

2

可以缓存对象:

var $outer = $('#outer-element'); 
$outer.find('.first-class').html('wanna'); 
$outer.find('.second-class').html('scope'); 
$outer.find('.third-class').html('better');