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
88 views
in Technique[技术] by (71.8m points)

javascript - Add a class attribute to certain links

I have pages on my site that go through a translation proxy. I need the displayed text in certain links to not be translated. I can add class="notranslate" to the link and the translator will skip over it no problem. However, I have hundreds of pages created before I implemented the translator and I'll have hundreds more as I keep going along—manually adding the class is not really an option.

The links I'm specifically concerned with are ones whose display text are literal URLs or email addresses. The translator doesn't touch the href attributes so the links still work as expected, but the displayed string gets mangled. For instance, in Vietnamese, "[email protected]" is displayed as "t? [email protected]," and a link whose display text should be "domain.com/committees" is translated to "domain.com/commitaries."

So I'm looking for a solution that finds a elements whose display text contains "@" or "/" and adds class="notranslate". I don't think I need too robust a solution as I otherwise don't use the "@" or "/" in link display text often, if ever, except in these situations. I would guess this could be done with Javascript, but I'm a JS beginner at best. An option that filters content on the backend through Wordpress could also be a nice solution.

question from:https://stackoverflow.com/questions/65861713/add-a-class-attribute-to-certain-links

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

1 Reply

0 votes
by (71.8m points)

This is simple using jquery, ideally this will need to load before your translations plugin.

Note: If you have jquery already loaded as most wordpress themes already do, then you can remove the first line from this code, which includes the jquery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
  $( document ).ready(function() {
    $("a").each(function() {
    
      let text = $(this).text();  
    
      if(text.includes("@")) {
        $(this).addClass('notranslate');
      }

      if(text.includes("/")) {
        $(this).addClass('notranslate');
      }
 
    })
});
</script>

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

...