2013-10-08 139 views
0

目標:我試圖限制所有名爲#boom1的DIV ID中的所有文本框。通過ID限制textarea字符jquery

問題:不能讓他們所有的(在我看來循環方法有問題)

$(函數(){

var maxL = 300; 

$('#boom1').each(function (i, div) { //I got lost with syntax over here 

    var text = $('#boom1').text(); 
    if(text.length > maxL) { 

     var begin = text.substr(0, maxL), 
      end = text.substr(maxL); 

     $('#boom1').html(begin) 
      .append($('<a class="readmore"/>').attr('href', '#').html('read more...')) 
      .append($('<div class="hidden" />').html(end)); 
    } 

}); 

$(document).on('click', '.readmore', function() { 
    $(this).next('.hidden').slideDown(750); 
})   

})

我會很高興,如果能夠得到一些幫助,語法..

感謝。

附加一個DEMO

+0

爲什麼你會有多個具有相同ID的div?那不是真的。這可能是你的問題的原因 – Bobby5193

回答

0

嘗試使用下面的代碼,做工精細

$(function() { 

    var maxL = 300; 


    $('.wp-caption-text').each(function (i, div) { 
     //alert("dfs"); 
     var text = $(this).text(); 
     if(text.length > maxL) { 

      var begin = text.substr(0, maxL), 
       end = text.substr(maxL); 

      $(this).html(begin) 
       .append($('<a class="readmore"/>').attr('href', '#').html('read more...')) 
       .append($('<div class="hidden" />').html(end)); 

     } 

    }); 

    $(document).on('click', '.readmore', function() { 
     $(this).next('.hidden').slideDown(750); 
    })   


}) 
+0

謝謝你!一個很好的解決方這很聰明,很快! 完美 –

+0

:)我的榮幸Max –

0
$(function() { 

    var maxL = 300; 

    $('#boom1').each(function() { // If you don't use them you won't need them here 

     var text = $('#boom1').text(); 
     if(text.length > maxL) { 

      var begin = text.substr(0, maxL), 
       end = text.substr(maxL); 

      $('#boom1').html(begin) 
       .append($('<a class="readmore"/>').attr('href', '#').html('read more...')) 
       .append($('<div class="hidden" />').html(end)); 
     } 

    }); 

    $(document).on('click', '.readmore', function() { 
     $(this).next('.hidden').slideDown(750); 
    }); 



}); 
0

DEMO

ID必須是唯一的。

使用多種用法的類。

添加boom類每格。

添加​​和read more...切換功能了。

$(this)是指在環中的當前元素。

$(function() { 
    var maxL = 300; 
    $('.boom').each(function (i, div) { 
     var text = $(this).text(); 
     if (text.length > maxL) { 

      var begin = text.substr(0, maxL), 
       end = text.substr(maxL); 

      $(this).html(begin) 
       .append($('<a class="readmore"/>').attr('href', '#').html('read more...')) 
       .append($('<div class="hidden" />').html(end)); 
     } 
    }); 
    $(document).on('click', '.readmore', function() { 
     $(this).html(function(_,ctr){ 
      return (ctr == 'read more...') ? 'read less...':'read more...' 
     }); 
     $(this).next('.hidden').slideToggle(750); 
    }); 
}); 
0

.each()讓你遍歷元素的所有情況,所以你不應該使用一個ID。以下內容將迭代每個「某個類」元素。

<div class="some-class"></div> 
<div class="some-class"></div>  


$('.some-class').each(function (i, div) {/* code*/ }); 
0

我不認爲你可以使用每個ID - 它只會讓你第一個。標識符應該是唯一的,每頁僅出現一次。所以只有第一個會被使用。

嘗試向每個'#boom1'添加一個類,例如'.boom-class',然後對其執行jQuery。