通过ID获取元素并在JavaScript中设置值

105
我有一个JavaScript函数,我向其中传递一个参数。该参数表示我的网页中一个元素(一个隐藏字段)的ID。我想要更改此元素的值。
function myFunc(variable) {
  var s = document.getElementById(variable);
  s.value = 'New value'
}

当我这样做时,会出现一个错误,提示无法设置值,因为对象为空。但是我知道该对象不为空,因为我在浏览器生成的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'
}

当警告消息出现时,两个参数都是相同的,但我仍然收到错误。但是当我这样做时,一切都正常。

  var s = document.getElementById('This-is-the-real-id');
  s.value = 'New value'

我该如何修复这个问题?

我要设置值的元素是一个隐藏字段,其ID是动态设置的,随着页面加载而变化。我已经尝试在$(document).ready函数中添加了这个,但它没有起作用。


2
让我们看看你在哪里调用函数(根据您提供的代码,该函数没有名称)。 - Anthony Grist
什么是变量?如何称呼未命名的函数? - mplungjan
当您在这种情况下进行诊断alert()console.log()时,您应该始终使用一些标记字符来包装值,以便您可以确定字符串中是否有杂散的空格字符。因此:alert("[" + x + "], [" + y + "]"); - Pointy
请在jsfiddle.net上展示一个这样的例子 - 你所问的并没有太多意义。 - Dennis
7个回答

88
如果在文本区域呈现到页面之前执行myFunc(variable),则会出现空异常错误。
<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 -->

因此,请确保您的文本区存在于页面上,然后调用myFunc。您可以使用window.onload$(document).ready函数。


我的代码看起来像这样 @Html.HiddenFor(m => m.myfield, new{id = "myId"}) <input type="button" onclick="javascript: myFunc(myID)" value="button"/>。 - jpo
只有在按钮被点击时才会调用该函数,而这只会发生在页面加载后。除此之外,我如何确保在按钮被点击之前所有的事情都已经发生了呢? - jpo
@jpo 在 onclick="javascript: myFunc(myID)" 中,myID 应该用单引号括起来。 - Xiaodan Mao
在按钮被点击之前进行设置。 - jpo
@jpo 这很奇怪,我的ID是否被单引号包裹?或者你的ID没有成功设置。你是否使用像Firebug这样的Web开发工具检查了ID?它是否存在? - Xiaodan Mao
显示剩余3条评论

27

给定

<div id="This-is-the-real-id"></div>

那么

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");
}

会做你想要的


给定

<input id="This-is-the-real-id" type="text" value="">

那么

function setValue(id, newvalue) {
  var s = document.getElementById(id);
  s.value = newvalue;
}

window.onload = function() {
  setValue("This-is-the-real-id", "Hello there");
}

会做你想要的

function setContent(id, newvalue) {
  var s = document.getElementById(id);
  if (s.tagName.toUpperCase() === "INPUT") 
    s.value = newvalue;
  else 
    s.innerHTML = newvalue;
}

window.addEventListener("load", function() {
  setContent("This-is-the-real-id-div", "Hello there");
  setContent("This-is-the-real-id-input", "Hello there");
})
<div id="This-is-the-real-id-div"></div>
<input id="This-is-the-real-id-input" type="text" value="">


正是我所想的。但是我的 id 和 set 是动态的。但是我使用了相同的思路。但当函数被调用时,文档无法找到指定 id 的元素。 - jpo
我们需要查看HTML和事件处理程序(例如onclick)。 - mplungjan

6
没有任何答案提到可以使用.setAttribute()来补充.value()的可能性:
document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");

这个附录实际上改变了页面源代码中值的内容,从而使这个值更新起来具有form.reset()的可靠性。


粗鲁?还是我错过了SO的规则? - Aiyion.Prime

4

使用:

<html>

<head>
    <script>
        function updateTextarea(element)
        {
            document.getElementById(element).innerText = document.getElementById("ment").value;
        }
    </script>
</head>

<body>
    <input type="text"
           value="Enter your text here."
           id = "ment"
           style = " border: 1px solid grey; margin-bottom: 4px;"
           onKeyUp="updateTextarea('myDiv')" />
    <br>

    <textarea id="myDiv" ></textarea>
</body>

</html>

3

对于每种元素类型,您可以使用特定的属性来设置值。

E.g.:

<div id="theValue1"></div>
window.document.getElementById("theValue1").innerText = "value div";

<input id="theValue2"></input>
window.document.getElementById("theValue2").value = "value input";

您可以在这里尝试示例!


1

试着像下面这样做。它会起作用的...

<html>

<head>
    <script>
        function displayResult(element)
        {
            document.getElementById(element).value = 'hi';
        }
    </script>
</head>

<body>
    <textarea id="myTextarea" cols="20">
        BYE
    </textarea>
    <br>

    <button type="button" onclick="displayResult('myTextarea')">Change</button>
</body>

</html>

2
内联事件处理程序是不良实践。 - jbabey

0

我认为问题在于你调用 JavaScript 函数的方式。

你的代码像这样:

<input type="button" onclick="javascript: myFunc(myID)" value="button"/>

myID 应该用引号括起来。


2
javascript:标签是完全不必要的。 - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接