簡體   English   中英

Vue2將類添加到重點輸入

[英]Vue2 add class to focused input

我有一個帶有許多輸入的表單,我想向集中的輸入標簽標記添加一個類,並在選擇另一個輸入時刪除該類。

我做這樣的代碼

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

但是如何在更改焦點時從一個輸入中刪除類並添加到另一個輸入中?

更新:

我找到了解決方案,但看起來很復雜:)

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);
     }
}

首先,您不清楚要做什么。 您已找到解決方案的第二個,因此只需清理代碼即可。 我嘗試使用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");

鏈接到文檔

使用此解決方案,您將節省更多。 麻煩您,讓我們想象一下有人更改了HTML結構...那么您的代碼停止工作的風險很高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM