将值推送到html并再次从JS获取

时间:2017-10-17 05:52:27

标签: javascript jquery

我想为隐藏输入分配一个值,然后使用输入id从javascript的下一部分获取该值。因此它将根据从javascript的第一部分分配的隐藏输入值来警告值。但是,这对我当前的任务来说很重要。我必须将值推送到HTML,然后在javascript变量中再次返回。如果您有任何解决方案,请告诉我。



<!DOCTYPE html>
    <html>
    <head>
        <title>Just test</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.18/pdfmake.min.js"></script>

    </head>
    <body>
<script>
    var myVal = "some string";
    $("#foo").val(myVal);
</script>

<input type="hidden" name="foo" id="foo" value="">


<script>
    var doo = "";
    doo = $(this).find("#foo").val();
    if (doo != "") {
        alert(doo);
    }else{
        alert("doo is null");
    }
</script>
    </body>
    </html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以使用等待所有DOM元素呈现的$(document).ready()方法。然后执行JS代码。您可以阅读更多相关信息here

&#13;
&#13;
<!DOCTYPE html>
    <html>
    <head>
        <title>Just test</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.18/pdfmake.min.js"></script>

    </head>
    <body>

        <script>
          $(document).ready(function(){
            var myVal = "some string";
             $("#foo").val(myVal);
          });
             
        </script>

        <input type="hidden" name="foo" id="foo" value="">


        <script>
          $(document).ready(function(){
            var doo = "";
            doo = $(this).find("#foo").val();
            if (doo != "") {
                alert(doo);
            }else{
                alert("doo is null");
            }
            
          });
        </script>
    </body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用HTMLFormControlsCollection Web API,我们可以非常轻松地引用任何和所有表单元素:

示例

 /* Find the first form of a page without knowing it's .class or #id */

   // HTMLFormControlsCollection        // Common way
   var form = document.forms[0];        var form = document.getElementsByTagName('form')[0];

演示

&#13;
&#13;
<!DOCTYPE html>
<html>

<head>
  <title>Just test</title>


</head>

<body>

  <form id='A'>
    <input id="X" name="X">
    <output id='Y' name='Y'></output>
    <input id='Z' name='Z' type='hidden'>
  </form>



  <script>
    var F = document.forms.A;

    F.oninput = function() {
      var X = F.X.value;
      var Y = F.Y;
      var Z = F.Z;
      Y.value = X;
      Z.value = X;
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;