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

我使用一个复选框来激活一些 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>


慕仙森
浏览 208回答 3
3回答

红糖糍粑

e.value 中有什么?它不包含复选框的直接值。这工作正常&nbsp; console.log(e.value)&nbsp; var value = 'quant_' + 1;&nbsp; var x = document.getElementById(value);&nbsp; console.log(x, 'hello');https://jsfiddle.net/5dom7wx8/16/

慕田峪4524236

您应该分配一个更通用的事件侦听器,而不是像这里那样使用内联处理程序。如果使用querySelectorAll就不需要使用getElementById,这在很多情况下是非常不方便的。由于上面的 javascript 函数似乎还没有做太多,也许您可以尝试这样的方法document.querySelectorAll('input[type="checkbox"]').forEach( chk=>{&nbsp; &nbsp; chk.addEventListener( 'click', function(e){&nbsp; &nbsp; &nbsp; &nbsp; if( this.checked ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert( this.value )&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })});

慕妹3242003

尽管有代码本身,为了使它符合您的解释,您应该将要更改的输入(我假设)的 id 传递给方法 updateInputsLabels:<td><input type="checkbox" name="product[]" value="<?=$row['product_id']?>" onchange="updateInputsLabels('<?=$row['product_id']?>')" checked></td>并改变你的方法:function updateInputsLabels(inputId){&nbsp; &nbsp; if(typeof inputId='string' && inputId.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; let fullId = 'quantity_' + inputId;&nbsp; &nbsp; &nbsp; &nbsp; let element = document.getElementById(fullId );&nbsp; &nbsp; &nbsp; &nbsp; console.log(fullId );&nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; console.error("not a string or empty");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP