简体   繁体   English

如何在对象名称中使用方法作为字符串?

[英]How can I use method on object which name I have as a string?

I'm coming back with another problem. 我回来了另一个问题。

I have such code: 我有这样的代码:

HTML 的HTML

<button>first</button>
<button>second</button>

<div class="first"></div>
<div class="second"></div>

CSS 的CSS

div{
  margin-top: 10px;
  width: 100px;
  height: 100px;
  border:1px solid black;
  background-color: #ddd;
}

JS JS

const btns = document.querySelectorAll("button");
const first = document.querySelector(".first");
const second = document.querySelector(".second");

btns.forEach(btn => btn.addEventListener("click", function(){
  this.classList.toggle("pressed");
  let selection = this.textContent;

  // selection.style.transform = "translate(100px)";
}))

https://codepen.io/ptr11dev/pen/oREymM https://codepen.io/ptr11dev/pen/oREymM

I'd like to create one function that'll be responsible for moving respective div to the right side by 100px - I stuck with such problem. 我想创建一个函数,该函数负责将相应的div向右移动100px-我陷入了这样的问题。 Under "selection" I have respective name of div (stored under the same name), but simple code like 在“选择”下,我有各自的div名称(以相同的名称存储),但是简单的代码如

selection.style.transform = "translate(100px);"

doesn't work. 不起作用。 I know that workaround like creating two functions and using 我知道这种解决方法,例如创建两个函数并使用

first.style.transform = "translate(100px);"

and

second.style.transform = "translate(100px);"

would work, but in my main code it's a bit more complicated. 可以工作,但是在我的主要代码中却有点复杂。

I'll really appreciate any input from your side. 我真的很感谢您的任何投入。 Thanks 谢谢

PS I'd like to use Vanilla JS. PS我想使用Vanilla JS。

Your problem is textContext is just that TEXT not an object. 您的问题是textContext只是TEXT不是对象。 This sets selection as the first element that matches the class name pulled as this.textContent; 这会将选择设置为与作为this.textContent拉出的类名匹配的第一个元素。

let selection = document.getElementsByClassName(this.textContent)[0];
selection.style.transform = "translate(100px)";

You can find them by the class name, assuming that the button text and their class are the same. 假定按钮文本和它们的类相同,则可以通过类名找到它们。

 const btns = document.querySelectorAll("button"); const first = document.querySelector(".first"); const second = document.querySelector(".second"); btns.forEach(btn => btn.addEventListener("click", function(){ this.classList.toggle("pressed"); let selection = this.textContent; document.querySelector(`.${selection}`).style.transform = "translate(100px)"; })) 
 div{ margin-top: 10px; width: 100px; height: 100px; border:1px solid black; background-color: #ddd; } 
 <button>first</button> <button>second</button> <div class="first"></div> <div class="second"></div> 

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

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