Javascript按ID获取元素并设置值

jpo*_*jpo 69 javascript default-value

我有一个javascript函数,我传递一个参数.该参数表示我的网页中元素(隐藏字段)的ID.我想改变这个元素的值.

function myFunc(variable){
  var s= document.getElementById(variable);
  s.value = 'New value'
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到一个错误,即无法设置该值,因为该对象为null.但我知道该对象不是null,因为我在浏览器生成的html代码中看到它.无论如何,我尝试了以下代码进行调试

function myFunc(variable){
  var x = variable;
  var y  = 'This-is-the-real-id'
  alert(x + ', ' + y)
  var s= document.getElementById(x);
  s.value = 'New value'
}
Run Code Online (Sandbox Code Playgroud)

当警报消息显示时,两个参数都相同,但我仍然得到错误.但是当我这样做时一切正常

  var s= document.getElementById('This-is-the-real-id');
  s.value = 'New value'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题呢

编辑

我设置值的元素是隐藏字段,id是动态det,因为页面加载.我试过在$(document).ready函数中添加了这个但是没有用

Xia*_*Mao 64

如果在textarea呈现为页面之前执行myFunc(变量),则会出现null异常错误.

<html>
    <head>
    <title>index</title>
    <script type="text/javascript">
        function myFunc(variable){
            var s = document.getElementById(variable);
            s.value = "new value";
        }   
        myFunc("id1");
    </script>
    </head>
    <body>
        <textarea id="id1"></textarea>
    </body>
</html>
//Error message: Cannot set property 'value' of null 
Run Code Online (Sandbox Code Playgroud)

因此,确保您的textarea确实存在于页面中,然后调用myFunc,您可以使用window.onload或$(document).ready函数.希望它有用.


mpl*_*jan 23

特定

<div id="This-is-the-real-id"></div>
Run Code Online (Sandbox Code Playgroud)

然后

function setText(id,newvalue) {
  var s= document.getElementById(id);
  s.innerHTML = newvalue;
}    
window.onload=function() { // or window.addEventListener("load",function() {
  setText("This-is-the-real-id","Hello there");
}
Run Code Online (Sandbox Code Playgroud)

会做你想做的


特定

<input id="This-is-the-real-id" type="text" value="">
Run Code Online (Sandbox Code Playgroud)

然后

function setValue(id,newvalue) {
  var s= document.getElementById(id);
  s.value = newvalue;
}    
window.onload=function() {
  setValue("This-is-the-real-id","Hello there");
}
Run Code Online (Sandbox Code Playgroud)

会做你想做的


Aiy*_*ime 6

没有答案提出使用.setAttribute()以下内容的可能性.value()

document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");
Run Code Online (Sandbox Code Playgroud)

这个附录实际上改变了页面源中值的内容,这反过来又使值form.reset()防更新。