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

标签 javascript html css web

这是我的代码:

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

我想写一个棋子移动的通用函数。我想要的只是,当一个人点击棋子,然后按下向上按钮时,它必须上升。

最佳答案

是的,你可以使用字符串变量:

HTML:

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

javascript:

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

jsfiddle here

关于javascript - 我可以在 document.getElementById() 中使用字符串变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22068387/

相关文章:

javascript - 基于右键单击从 html 的特定部分中抓取

android - Jquery Mobile 面板随内容滚动

java - 与元素类型 "href"关联的属性 "null"的值不得包含 '<' 字符

javascript - 组件内的处理程序错误地调用了彼此的代码

javascript - 使用或不使用 string.slice 对字符串中的字符进行计数

html - 如何更改语义 ui 中的输入大小?

javascript - 使用 javascript 移动 div 会导致位置 :relative to position:static 发生意外更改

javascript - 如何使元素在滚动时仅显示在容器上

javascript - 在 THREE.js 中在 Canvas 来源的纹理上进行透明绘图

jquery - 如何在多个类(超过 2 个)之间切换?