Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Replace li text using jquery

I am trying to replace the content of li and tags.

Tried below code.

   <html>
    <head>Sample</head>
   <body>
    <a href="#"><input type="checkbox" class="layer-input-filter" name="testname">Test <span class="count">5</span>      </a>

    <a href="#"><input type="checkbox" class="layer-input-filter" name="testname1">Test1 <span class="count">10</span> </a>

 <ul>
  <li><a href="#" rel="noopener">Mixed assessment guidelines</a></li>
  <li><a href="" target="_blank" rel="noopener">Specimen </a></li>
  <li><a href="#" rel="noopener">Plagiarism </a></li>
  <li><a href="" target="_blank" rel="noopener">Download </a></li>
  <li><a href="#" rel="noopener">Qualification update</a></li>
  <li><a href="" target="_blank" rel="noopener">Specimen</a></li>
  <li><a href="#" rel="noopener">Exam guide update</a></li>
  <li><a href="" target="_blank" rel="noopener">Guide </a></li>
 </ul>

  <script>
     $(document).ready(function($) {
      var value = 0.4;
      $("body").find('li').each(function (index) {
                if ($(this).text() != '') {

                    var str = $(this).clone().children().remove().end().text();
                    var newstring =  str + str.substring(0, str.length  * value);
                    $(this).text(newstring);
                }
            });
    });
   </script>
 </body>

  </html>

I need to replace the text of every li inside the body. so used above jquery for it. But its not working.

Example :

  <li><a href="#" rel="noopener">Plagiarism </a></li>

Should replace as

   <li><a href="#" rel="noopener">PlagiarismPlag </a></li>

First four characters of each li text. That is Plag in above example

Can anyone help me with this, please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the problem is with the line

 var str = $(this).clone().children().remove().end().text();

The order of the functions makes the string empty in the end. If you replace it with

 var str = $(this).text();

it works.

I'm not sure what your line is trying to achieve, but the problem is there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...