在類別頁面中,每個帖子都有不同的摘錄。我需要根據窗口寬度使用javascript修剪這些摘錄。我刪除了窗口寬度的代碼,因爲它不相關。我的問題是,當前的代碼將替換所有的摘錄與第一個。顯然是因爲theString
取第一個值。更改類別頁面上每個帖子的摘錄
你可以在這裏看到代碼:
function trimWords(){
var contentWidth = $(window).width(); //get width of browser
var maxLength = 20 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = theString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
$(".trimmed-words").html(trimmedString);
}
if ($(".trimmed-words").length > 0){
var theString = $(".trimmed-words").html(); //issue here. it takes only the first value from the first div
trimWords();
$(window).resize(trimWords)
}
\t \t
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="individual-post">
<div class="trimmed-words">
first first first first first first first
</div>
</div>
<div class="individual-post">
<div class="trimmed-words">
second second second second second second
</div>
</div>
<div class="individual-post">
<div class="trimmed-words">
third third third third third third third
</div>
</div>
<div class="individual-post">
<div class="trimmed-words">
fourth fourth fourth fourth fourth fourth
</div>
</div>
我需要做的東西沿着這些路線:
$(".individual-post").each(function(){ //loop through every div
var theString = $(this).find(".trimmed-words").html();
trimWords(theString);
});
但我不能設法轉移的價值的theString
。
我會很感激任何幫助,將指向我的正確方向。
謝謝。
你需要得到作爲一個參數'theString'一個循環中通過'。個別-POST'元素 – abidibo 2015-03-19 11:47:26