简体   繁体   中英

Accessing a variable from outside the function?

I have a Javascript function and would like to retrieve the id value from outside the function. How can make "id" a static variable and access it from outside the function.

<input type="text" name="editinput" id="editinputtext" placeholder="Type Contribution...">
      <script>
          $(".contributions").click(function(){
          var id = this.id;
   });
document.getElementById("editinputtext").value = id;

You just need to declare variable outside of function.

<script>
  var id;
  $(".contributions").click(function(){
     id = $(this).attr("id");
   });
  document.getElementById("editinputtext").value = id;
</script>

I think what you're trying to do is simpler than you make it out to be. The variable id will not have any value and will be undefined until the actual click function is called.

So what you can do is define the variable within the click function and assign it straight to editinputtext . But you're also using jQuery so you can also assign it in this way.

<input type="text" name="editinput" id="editinputtext" placeholder="Type Contribution...">

<script>
   $(".contributions").click(function(){
      var id = this.id;
      $("#editinputtext").val(id);
   });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM