简体   繁体   English

从类中的purejs中显示第1个2个字符,其余的隐藏

[英]Show 1st 2 characters in purejs from the class and hide the rest

I want to show the first 2 letters ie, En . 我想显示前2个字母,即En I want to use Pure JS to finish this. 我想使用Pure JS完成此操作。 There is no changes whatsoever. 没有任何变化。 I have tried to add the JS in both header and footer, still no change on the site. 我试图在页眉和页脚中都添加JS,但网站上仍然没有更改。

HTML: HTML:

<a href="#" class="myclassname">English</a>

JS: JS:

var i;
var sheb = document.getElementsByClassName("myclassname");
for(i=0;i<sheb.length;i++) {
  if(sheb[i].className == 'myclass') {
    sheb[i].innerHTML = sheb[i].innerHTML.substring(0,3);
  }
}

You made a mistake in your if statement; 您在if语句中犯了一个错误; you check if the className is myclass instead of myclassname . 您检查className是myclass而不是myclassname Also, you should use substring(0,2) instead of substring(0,3) . 另外,您应该使用substring(0,2)而不是substring(0,3)

Apart from those 2 mistakes, it works fine: 除了这两个错误之外,它还可以正常工作:

 var i; var sheb = document.getElementsByClassName("myclassname"); for(i=0;i<sheb.length;i++) { if(sheb[i].className == 'myclassname') { sheb[i].innerHTML = sheb[i].innerHTML.substring(0,2); } } 
 <a href="#" class="myclassname">English</a> 

You have two issues: 您有两个问题:

There is a mismatch between the class name used in HTML ( myclassname ) and in JavaScript ( myclass ). HTML( myclassname )和JavaScript( myclass )中使用的类名不匹配。

Then your are taking up to 3 character with .substring(0,3) . 然后,您使用.substring(0,3)占用最多3个字符。 Here the second argument ( 3 ) is the length to take from the string. 这里的第二个参数( 3 )是从字符串中获取的长度。 You have to change that to .substring(0,2) . 您必须将其更改为.substring(0,2)

Try the following way: 请尝试以下方式:

 var i; var sheb = document.getElementsByClassName("myclass"); for(i=0;i<sheb.length;i++) { if(sheb[i].className == 'myclass') { sheb[i].innerHTML = sheb[i].innerHTML.substring(0,2); } } 
 <a href="#" class="myclass">English</a> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM