【问题标题】:Javascript Get Element by Id and set the valueJavascript通过Id获取元素并设置值
【发布时间】:2013-01-16 22:26:30
【问题描述】:

我有一个 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 函数中添加这个但没有工作

【问题讨论】:

  • 让我们看看你在哪里调用了这个函数(从你提供的代码来看,它没有名字)。
  • 什么是变量?以及如何调用未命名的函数?
  • 当您在这种情况下进行alert()console.log() 诊断时,您应该始终用一些标记字符包装值,这样您就可以判断是否有杂散空间字符串中的字符。所以:alert("[" + x + "], [" + y + "]");
  • 请在 jsfiddle.net 上展示一个发生这种情况的例子 - 你问的不是真的。

标签: javascript default-value


【解决方案1】:

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

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

虽然不太可能对最初的提问者有帮助, 这个附录实际上改变了 pages 源中值的内容, 这反过来又使值更新form.reset()-proof。

我希望这对其他人有帮助。

(或者我在半年后忘记 js 怪癖的时候......)

【讨论】:

    【解决方案2】:

    给定

    <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 和动态设置。但我使用了相同的想法。但是当我调用函数时,文档找不到指定id的元素
    • 我们需要查看 html 和事件处理程序(onclick 或其他)
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      myID 应该用引号括起来。

      【讨论】:

      • javascript: 标签完全没有必要
      【解决方案5】:
      <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>
      

      【讨论】:

        【解决方案6】:

        如果 myFunc(variable) 在 textarea 渲染到页面之前执行,你会得到 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 
        

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

        【讨论】:

        • 我创建隐藏字段,然后创建执行设置隐藏字段值的功能的按钮。但是,id 是动态设置的。我尝试在 $(document).ready 函数中添加此函数,但出现了同样的问题。
        • @jpo 如果 id 是动态设置的,您还应该确保在设置 id 之后调用 myFunc。您可以尝试在设置 id 的函数中调用 myFunc。
        • 我的代码看起来像这样 @Html.HiddenFor(m => m.myfield, new{id = "myId"}) .
        • 该函数仅在单击按钮时调用,并且仅在页面加载后发生。我还能如何确保在单击按钮之前一切都发生?
        • @jpo 在 onclick="javascript: myFunc(myID)" 中,myID 应该用单引号括起来。
        【解决方案7】:

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

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

        【讨论】:

        • 内联事件处理程序是不好的做法。
        猜你喜欢
        • 1970-01-01
        • 2015-09-02
        • 2011-12-10
        • 2010-12-18
        • 2017-05-26
        • 2012-06-08
        • 1970-01-01
        相关资源
        最近更新 更多