Javascript Javascript通过Id获取元素并设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14649173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:30:37  来源:igfitidea点击:

Javascript Get Element by Id and set the value

javascriptdefault-value

提问by jpo

I have a javascript function to which I pass a parameter. The parameter represents the id of an element (a hidden field) in my web page. I want to change the value of this element.

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

function myFunc(variable){
  var s= document.getElementById(variable);
  s.value = 'New value'
}

When I do this, I get an error that the value cannot be set because the object is null. But I know the object is not null because I see it in the html code generated by the browser. Anyways, I tried the following code to debug

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

When the alert message shows up, both parameters are the same, but I still get the error. But everything works fine when I do

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

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

How can I fix this please

我该如何解决这个问题

EDIT

编辑

The element for which I am setting the value is hidden field and the id is det dynamically, as the page loads. I have tried added this in the $(document).ready function but did not work

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

采纳答案by Xiaodan Mao

If myFunc(variable) is executed before textarea is rendered to page, you will get the null exception error.

如果在将 textarea 呈现到页面之前执行 myFunc(variable),您将收到 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 

So, make sure your textarea does exist in the page, and then call myFunc, you can use window.onload or $(document).ready function. Hope it's helpful.

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

回答by mplungjan

Given

给定的

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

then

然后

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

will do what you want

会做你想做的



Given

给定的

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

then

然后

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

will do what you want

会做你想做的

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="">

回答by Dah Moymy

<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>

回答by Darlan Dieterich

For each element type, you can use specific attribute to set value. E.g.:

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

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

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

You can try example here!

您可以在此处尝试示例!

回答by Pandian

try like below it will work...

像下面这样尝试它会起作用......

<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>

回答by K.I

I think the problem is the way you call your javascript function. Your code is like so:

我认为问题在于您调用 javascript 函数的方式。你的代码是这样的:

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

myID should be wrapped in quotes.

myID 应该用引号括起来。

回答by Aiyion.Prime

Coming across this question, no answer brought up the possibility of using .setAttribute()in addition to .value()

遇到这个问题,没有答案提出.setAttribute()除了使用的可能性.value()

document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");

Though unlikely helpful for the original questioner, this addendum actually changes the content of the value in the pages source, which in turn makes the value update form.reset()-proof.

尽管对原始提问者不太可能有帮助,但此附录实际上更改了页面源中值的内容,从而使值更新成为form.reset()证明。

I hope this may help others.

我希望这可以帮助其他人。

(Or me in half a year when I've forgotten about js quirks...)

(或者半年之后我忘记了js的怪癖……)