2012-07-18 55 views
2

基本上,我试图改变一个textarea的高度根据它有多少行,这是一种无关紧要的问题,但这里是编码添加事件监听器,而不使用for循环的每个textarea:如何在不使用for循环的情况下更改多个jQuery选定对象的样式?

$('textarea').keyup(function(event) { 
    this.style.height = Math.floor(this.scrollHeight/11) + '.1em'; 
}); 

这里是我的for循环:

for (i=0; i<$('textarea').length; i++) { 
    $('textarea')[i].style.height = Math.floor($('textarea')[i].scrollHeight/11) + '.1em'; 
} 

for循环的作品完美,但只是为了清洁和高效编码的缘故,我想它看起来更像没有第一编码循环被需要。

此外,一个注意,这是所有这一切,如果文件是准备好功能。

+0

使用循环。这是循环的目的。没有人就无法做到这一点。你可能会考虑一个'.each'循环,如下所示,但它仍然是一个循环。 – meagar 2012-07-18 03:51:26

回答

4

你可以尝试each()方法:

$('textarea').each(function(){ 
    $(this).css('height', Math.floor(this.scrollHeight/11) + '.1em') 
}) 

jQuery.each()

3

我是有点晚了,我与顶级答案达成一致! +1

$('textarea').each(function(ele){ 
    ele.style.height = Math.floor(ele.scrollHeight/11) + '.1em'; 
}}; 
2
$('textarea').keyup(function(event) { 

    // change height of all textarea including current 
    $('textarea').css('height', Math.floor(this.scrollHeight/11) + '.1em'); 

    // But using this like following 
    // will change height of current textarea 

    // $(this).css('height', Math.floor(this.scrollHeight/11) + '.1em'); 

}); 
0
$('textarea').keyup(function() { 

     $("textarea").each(function() { 
     this.height(Math.floor(this.scrollHeight/11) + '.1em') 

     }); 
    }); 
0

我想提高通过thecodeparadox答案。

var jq_textarea = $('textarea'); 
jq_textarea.keyup(function(event) { 
    jq_textarea.css('height', Math.floor(this.scrollHeight/11) + '.1em'); 
}); 

基本上,它可以节省您在每个关键笔画上的DOM遍历。

相关问题