简体   繁体   English

我可以在 document.getElementById() 中使用字符串变量吗?

[英]Can I use a string variable in document.getElementById()?

here is my code:这是我的代码:

function figureSelector () {
    document.getElementById("rook").onclick = function  () {
        curr = '"rook"';
    };
};

function moveLine(){
    document.getElementById("upButton").onclick = function() { 
            document.getElementById(curr).style.top = document.getElementById(curr).offsetTop - getPix() * 62  + "px"; 
            counter= counter + getPix();
    }; 

I want to write an universal function for a chess piece to move.我想写一个通用的function让棋子走。 All I want is, when one clicks the chess piece, and then presses the up button, it must go up.我想要的只是,当一个人点击棋子,然后按下向上按钮时,它必须 go 向上。

Yes you can use String variable: 是的你可以使用String变量:

HTML: HTML:

<div id="name" style="width:300px;height:300px;background:red"></div>

javascript: JavaScript的:

var b = 'name';
document.getElementById(b).innerHTML = 'none';

jsfiddle here jsfiddle在这里

Yes, you can. 是的你可以。 Just use 只是用

curr = 'rook';

(without the extra quotes) (没有额外的报价)

You can even do stuff like this: 你甚至可以这样做:

function mark(yy)  {
    for (var ii = 0; ii < 7; ii++ )  {
        if (  ii == yy )  {
            document.getElementById("b"+ii).style.fontWeight = "bold";
         }
...

But be careful of your loop limits to be sure you have a matching id. 但要小心你的循环限制,以确保你有一个匹配的ID。 I just spent hours trying to figure out why ("b"+ii) was getting error and finally realized that the error was being caused by exactly that. 我花了好几个小时试图弄清楚为什么("b"+ii)出现错误并最终意识到错误是由此引起的。 duh... 咄...

Yes, Mate, you can.是的,伙计,你可以。

You can use a variable as the argument for any function. That's just how functions work -- they don't care where the argument comes from.您可以使用变量作为任何 function 的参数。函数就是这样工作的——它们不关心参数来自哪里。 You should define curr outside those functions.您应该在这些函数之外定义 curr 。

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

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