2017-08-08 6 views
1

私はpタグの配列を持っており、配列内のpタグごとにsubstring(0,5)とし、前のものを置き換えたいと思います。しかし、私のコードは正しく動作していません。

HTML:配列内のすべてのタグpの5文字を​​部分文字列にする方法は?

<div class="test1"> 
    <p class="cls">1.Im try to use the click function </p> 
    <p class="cls">2.Im try to use the click function </p> 
    <p class="cls">3.Im try to use the click function </p> 
</div> 

JS:

$(document).ready(function() { 
    $('.cls').each(function() { 
     var iTotalWords = $(this).text().split(' '); 
     for (i = 0 ; i < iTotalWords.length; i++) { 
      var result = iTotalWords.substring(0, 50); 
      $(".cls").html(result);​ 
     } 
    }); 
}); 
+0

は、なぜあなたはテキストを分割するのですか? –

答えて

3

いくつかの問題。

ジェネリックセレクターは使用しないでください。あなたはthisの現在の要素を使用する必要があります。

完全なテキストを取得して部分文字列にするだけでループや分割は不要です。

文字列に50文字が含まれないため、部分文字列(0、50)を使用すると問題が発生します。 0,5の意味ですか?


$(document).ready(function() { 
 
    $('.cls').each(function() { 
 
     var iTotalWords = $(this).text();   
 
     var result = iTotalWords.substr(0, 5); 
 
     $(this).html(result); }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="test1"> 
 
    <p class="cls">1.Im try to use the click function </p> 
 
    <p class="cls">2.Im try to use the click function </p> 
 
    <p class="cls">3.Im try to use the click function </p> 
 
</div>

2

私はあなたが5つの文字または5つのワードを取得したい場合は確信しているので、私は両方用意しました。

.cls要素を取得し、.each()を使用して繰り返します。各段落でテキストを取得し、部分文字列またはスライスを使用して必要なものを取得します。まあ

/** five characters **/ 
 
$('.test1 .cls').each(function() { 
 
    $(this).text($(this).text().substring(0, 5)); 
 
}); 
 

 
/** five words **/ 
 
$('.test2 .cls').each(function() { 
 
    $(this).text($(this).text().split(' ').slice(0, 5).join(' ')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="test1"> 
 
    <p class="cls">1.Im try to use the click function </p> 
 
    <p class="cls">2.Im try to use the click function </p> 
 
    <p class="cls">3.Im try to use the click function </p> 
 
</div> 
 

 
<div class="test2"> 
 
    <p class="cls">1.Im try to use the click function </p> 
 
    <p class="cls">2.Im try to use the click function </p> 
 
    <p class="cls">3.Im try to use the click function </p> 
 
</div>

1

甘いとシンプルな

$(document).ready(function() { 
    $('.cls').each(function() { 
      console.log("with substr(start,end) ::"+$(this).text().substr(0,4)); 
    }); 
}); 
0

あなただけの、次のようにあなたは、単に行うことができ、純粋なJSでそうすることを選択した場合、

document.querySelectorAll('div.test1 > p') 
 
     .forEach(p => p.textContent = p.textContent.substr(0,5));
<div class="test1"> 
 
    <p class="cls">1.Im try to use the click function </p> 
 
    <p class="cls">2.Im try to use the click function </p> 
 
    <p class="cls">3.Im try to use the click function </p> 
 
</div>

関連する問題