Javascript按ID获取元素并设置值 [英] Javascript Get Element by Id and set the value

查看:1347
本文介绍了Javascript按ID获取元素并设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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'

我该怎样解决这个问题

编辑

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

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

推荐答案

如果执行了myFunc(变量)在将textarea呈现为页面之前,您将获得null异常错误。

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

<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 

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

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.

这篇关于Javascript按ID获取元素并设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆