【问题标题】:How to mix string with variables in an input needing mutiple values in js? (In this case, the coord attribute of the area tag)如何在需要js中多个值的输入中将字符串与变量混合? (本例中为 area 标签的 corrs 属性)
【发布时间】:2021-10-18 04:25:17
【问题描述】:

所以到目前为止我一直面临的问题是我目前正在尝试使用 javascript,以便根据一些变量设置我的 area 标签的 coords 属性(它是什么并不重要)。但是,坐标需要 4 个输入 (x1,y1,x2,y2),并且我有一些我不会使用该变量的值。这意味着我必须在输入中混合字符串和变量,而我不知道该怎么做。

为了让您更好地了解我在做什么,这里是一个摘要:

var p = some random value
var q = some random value

var a1 = document.getElementById(areaID);
a1.setAttribute("coords", "0,0, p,q")

当然这不起作用,因为 "" 使它认为 p,q 是字符串而不是变量。所以我尝试了其他方法都失败了(一些绝望的尝试)。

a1.setAttribute("coords", 0,0,p,q);
a1.setAttribute("coords", "0,0," + p + "," + q);
document.getElementById(areaID).coords = 0,0, p,q;

const list = ["0","0", p,q];
a1.setAttribute("coords", list);

那么有谁知道我怎么可能做到这一点?

【问题讨论】:

    标签: javascript html area coords


    【解决方案1】:

    您尝试的第二个选项应该有效。在您的示例中,areaID 是变量还是元素的实际 id?如果是后者,则需要用引号括起来:document.getElementById("areaID")

    var p = "val1"
    var q = 23
    
    var a1 = document.getElementById("areaID");
    a1.setAttribute("coords", "0,0," + p + "," + q)
    
    console.log(a1);
    <div id="areaID"></div>

    【讨论】:

    • 抱歉,我忘记添加“”,因为 areaID 是 id。但是,在我的实际程序中,我检查并包含“”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2015-12-19
    • 2011-07-19
    • 1970-01-01
    相关资源
    最近更新 更多