为了账号安全,请及时绑定邮箱和手机立即绑定

Document.GetElementById(VARIABLE) 不起作用,仅适用于字符串

Document.GetElementById(VARIABLE) 不起作用,仅适用于字符串

PHP
慕仙森 2021-11-05 15:08:13
我使用一个复选框来激活一些 javascript,它应该从页面中获取一个元素并更改它。问题是当我使用 document.getElementID(x) 时它返回一个空值,但是当我用硬编码的 id 替换 x 时它工作正常。问题是我希望它不是硬编码的,因为页面是动态的。我已经检查了变量 x 是否已分配以及元素是否已分配了 ID。<script type="text/javascript">    function updateInputsLabels(e){        if(e.checked){            //If True            var value = 'quantity_' + e.value;            var x = document.getElementById(value);// this is what doesnt work unless I hard-code the ID value             console.log(x);        }else {            //if false            var cellUnchecked = document.getElementById(e.value);        }    }</script>
查看完整描述

3 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

e.value 中有什么?


它不包含复选框的直接值。这工作正常



  console.log(e.value)

  var value = 'quant_' + 1;

  var x = document.getElementById(value);

  console.log(x, 'hello');

https://jsfiddle.net/5dom7wx8/16/


查看完整回答
反对 回复 2021-11-05
?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

您应该分配一个更通用的事件侦听器,而不是像这里那样使用内联处理程序。如果使用querySelectorAll就不需要使用getElementById,这在很多情况下是非常不方便的。由于上面的 javascript 函数似乎还没有做太多,也许您可以尝试这样的方法


document.querySelectorAll('input[type="checkbox"]').forEach( chk=>{

    chk.addEventListener( 'click', function(e){

        if( this.checked ){

            alert( this.value )

        }

    })

});


查看完整回答
反对 回复 2021-11-05
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

尽管有代码本身,为了使它符合您的解释,您应该将要更改的输入(我假设)的 id 传递给方法 updateInputsLabels:


<td><input type="checkbox" name="product[]" value="<?=$row['product_id']?>" onchange="updateInputsLabels('<?=$row['product_id']?>')" checked></td>

并改变你的方法:


function updateInputsLabels(inputId){



    if(typeof inputId='string' && inputId.length > 0){

        let fullId = 'quantity_' + inputId;

        let element = document.getElementById(fullId );

        console.log(fullId );



    }else {

        console.error("not a string or empty");

    }

}


查看完整回答
反对 回复 2021-11-05
  • 3 回答
  • 0 关注
  • 207 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信