用字符串寻址变量

Addressing variable with string

我想根据用户点击的按钮在段落上写 hello。我尝试了以下但没有帮助。我该怎么做?

const para1 = document.getElementById('para1');
const para2 = document.getElementById('para2');

const options = document.getElementsByClassName('option');
for (let i = 0; i < options.length; i++) {
  let foo = options[i].classList[1];
  options[i].addEventListener('click', () => {
    process(foo)
  })
}

function process(x) {
  let goo = `para${x}`; //This doesn't work
  goo.textContent = "hello";
  console.log(x);
  console.log(goo);
}
#para1 {
  width: 50px;
  height: 50px;
  background: blue;
}

#para2 {
  width: 50px;
  height: 50px;
  background: red;
}
<button class="option 1">Write on para1</button>
<button class="option 2">Write on para2</button>
<p id="para1"></p>
<p id="para2"></p>

您正试图在字符串而不是元素上设置 属性 textContent。您需要传递找到的元素,而不是方法 process 中的字符串 x

const para1 = document.getElementById('para1');
const para2 = document.getElementById('para2');

const options = document.getElementsByClassName('option');
for (let i = 0; i < options.length; i++) {
  let option = options[i];
  options[i].addEventListener('click', () => {
    process(option); // passing the element button.option
  })
}

function process(option) {
  const x = option.classList[1]; // get second class name
  const para = document.getElementById(`para${x}`); // find paragraph by id
  para.textContent = "hello"; // set text on paragraph
}
#para1 {
  width: 50px;
  height: 50px;
  background: blue;
  color: white;
}

#para2 {
  width: 50px;
  height: 50px;
  background: red;
  color: white;
}
<button class="option 1">Write on para1</button>
<button class="option 2">Write on para2</button>
<p id="para1"></p>
<p id="para2"></p>

您正在尝试设置字符串而不是 DOM 节点的 textContent。

function process(x) {
  let goo = document.getElementById(`para${x}`); //Try this instead
  goo.textContent = "hello";
  console.log(x);
  console.log(goo);
}

更新线路

let goo = `para${x}`; //This doesn't work

let goo = window['para'+x];

应该可以

访问 javascript 变量作为字符串是用方括号 [] 语法完成的:

//global variables:
var foo = "hello";
var bar = "foo";
console.log(window[bar]); //prints "hello"

//for objects:
var someObject = {
  "foo": "hello"
};
var bar = "foo";
console.log(someObject[bar]);