使用Javascript(而不是jQuery!)在多个表单标签上执行字数统计

时间:2021-08-17 07:54:51

I have multiple labels as part of my form and I'm unable to attach classes to them individually due to the constraints of the system I'm working within and they don't contain IDs. I need to style the labels differently depending on their content, e.g. if it has less than 5 words then I will style it one way, if it has more than 5 words I will style it another. I need to find a way to dynamically add a class to the label depending on whether it has less or more than 5 words.

我有多个标签作为我的表单的一部分,我无法单独附加类,因为我正在使用的系统的约束,他们不包含ID。我需要根据标签的内容对标签进行不同的样式设置,例如:如果它少于5个单词,那么我将以一种方式设置它,如果它有超过5个单词,我将另外设置它。我需要找到一种方法来动态地将类添加到标签,具体取决于它是否少于或多于5个单词。

2 个解决方案

#1


0  

You can do something like this:

你可以这样做:

var labels = document.getElementsByTagName("label");


for(let ii = 0; ii < labels.length; ii++){
    let currentLabel = labels[ii];
    let words = currentLabel.innerHTML.split(' ');

  if(words.length >= 5)
  {
        currentLabel.className = "bold"
  }


}

Here is a JsFiddle showing the example.

这是一个显示示例的JsFiddle。

#2


0  

Is this what you meant: http://codepen.io/zvona/pen/BzVkqm

这是你的意思:http://codepen.io/zvona/pen/BzVkqm

window.addEventListener('DOMContentLoaded', onLoad, false);

function onLoad() {
  [].forEach.call(document.querySelectorAll('label'), assignClasses); 
}

function assignClasses(elem) {
  var words = elem.textContent.split(' ');

  elem.classList.add((words.length <= 5) ? 'fiveOrLess' : 'moreThanFive');
}

#1


0  

You can do something like this:

你可以这样做:

var labels = document.getElementsByTagName("label");


for(let ii = 0; ii < labels.length; ii++){
    let currentLabel = labels[ii];
    let words = currentLabel.innerHTML.split(' ');

  if(words.length >= 5)
  {
        currentLabel.className = "bold"
  }


}

Here is a JsFiddle showing the example.

这是一个显示示例的JsFiddle。

#2


0  

Is this what you meant: http://codepen.io/zvona/pen/BzVkqm

这是你的意思:http://codepen.io/zvona/pen/BzVkqm

window.addEventListener('DOMContentLoaded', onLoad, false);

function onLoad() {
  [].forEach.call(document.querySelectorAll('label'), assignClasses); 
}

function assignClasses(elem) {
  var words = elem.textContent.split(' ');

  elem.classList.add((words.length <= 5) ? 'fiveOrLess' : 'moreThanFive');
}