简体   繁体   English

Vue2将类添加到重点输入

[英]Vue2 add class to focused input

froI have a form with many inputs and I want to add a class to focused input label tag and remove class when another input selected. 我有一个带有许多输入的表单,我想向集中的输入标签标记添加一个类,并在选择另一个输入时删除该类。

I make such code 我做这样的代码

  onInputSelected: function(e) {
     var label =  e.target.previousElementSibling;
     label.classList.add('highlight');
  }

but how can I remove class from one input and add to another when I change focus? 但是如何在更改焦点时从一个输入中删除类并添加到另一个输入中?

Updated: 更新:

I found solution but looks like it's to complicated :) 我找到了解决方案,但看起来很复杂:)

data: {
    allInputs: document.getElementsByTagName('input')
},
methods: {
    onInputSelected: function(e) {
        e.target.previousElementSibling.classList.add('highlight');
        [].forEach.call(this.allInputs, function (currentValue, index) {
             if(currentValue.name ==  this.name) {
                 return;
             }

              currentValue.previousElementSibling.classList.remove('highlight');
        }, e.target);
     }
}

First of all you're not being very clear what you want to do. 首先,您不清楚要做什么。 2nd of all you have found solution so just clean up your code. 您已找到解决方案的第二个,因此只需清理代码即可。 3rd of all I'd try using el.closest. 我尝试使用el.closest的所有方法中的第3个。

const input = document.getElementById('yourInput');
const label = input.closest("label");
// or if you want to add ids to labels
const label2 = input.closest("#yourLabel");

Link to docs 链接到文档

With this solution you will be little bit more save. 使用此解决方案,您将节省更多。 Couse in yours, lets just imagine that somebody change HTML structure... Then very high risk your code stops working. 麻烦您,让我们想象一下有人更改了HTML结构...那么您的代码停止工作的风险很高。

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

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