【发布时间】:2012-01-09 17:02:44
【问题描述】:
我正在尝试让我的 javascript 在 DOM 中动态查找元素 ID。
我正在使用这个
var string = "retail";
document.getElementById('markup_'+string+'_percentage').value=z.toFixed(2)+"%";
变量 "string" 的值类似于 "retail"
我认为这会给出“markup_retail_percentage”的串联字符串。
但它实际上将其作为错误消息给出:
document.getElementById("markup_"+string+"_percentage") is null
我也尝试过使用“。”和“ * ”运算符。
我的一个 html 元素
<input type="text" id="markup_retail_percentage" size="5" name="markup_retail_percentage" value="" readonly />
解决方案!!!!
//using a new variable name to be passed to function
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
【问题讨论】:
-
你的意思是漏掉
'percentage'之前的下划线吗? -
您能否发布元素的 id 为 markup_retail_percentage 的 html 代码?
-
你真的需要stackoverflow吗?只需查看以下警报中的内容 alert('markup_'+ string +'percentage'); - 这意味着变量字符串不正确 alert(document.getElementById('markup'+ string +'_percentage')); - 如果警报 1 很好,如果警报 2 给出 null,那么您的文档中没有该 ID 的元素
-
@AdelBoutros ;提出的解决方案。看来是串联或变量名问题
-
如果你写了
elementid = 'markup_' + elementid + '_percentage',它也会起作用。
标签: javascript string concatenation