【问题标题】:Alternative to This in JavascriptJavascript 中的替代方法
【发布时间】:2017-04-06 17:38:48
【问题描述】:

我在 codepen 上有这个代码:https://codepen.io/RaoniSousa/pen/Zpkxbb:

var x = document.querySelectorAll('.label'), //label com ID label,
    z = document.querySelectorAll('.input'); //input com ID name;

function myFunction() {
'use strict';
if (this.value !== "" ) {
    this.style.opacity = '1';
    this.style.bottom = '4em';
    this.style.color = '#722872';
    console.log(this);
} else {
    this.style.opacity = '0';
    this.style.bottom = '1.5em';
    console.log(this);
    }
}

在上面的函数中,我只想更改标签 (var x) 的样式。我知道 'this' 指的是 .input (var z),但是,当我更改他的相关输入值时,我想将样式应用于标签,但如果我使用 for 循环,他会同时调用所有标签。有没有办法通过使用 'this.style' 来调用 var x 而不是 var z,或者有人知道此代码的另一种替代方法?

我希望它像这里发生的那样工作(向下滚动直到到达 联系我 部分):https://codepen.io/freeCodeCamp/pen/YqLyXB

提前致谢。

【问题讨论】:

    标签: javascript arrays input this selectors-api


    【解决方案1】:

    试试这个

    function myFunction() {
        'use strict';
        if (this.value !== "" ) {
            this.nextElementSibling.style.opacity = '1';
            this.nextElementSibling.style.bottom = '2em';
            this.nextElementSibling.style.color = '#722872';
            console.log(this.nextElementSibling);
        } else {
            this.style.opacity = '.4';
            this.style.bottom = '.5em';
            console.log(this);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2011-09-24
      • 2012-10-18
      • 1970-01-01
      • 2014-12-17
      • 2017-04-05
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多