首页 > 解决方案 > How to use a variable after it was a jquery function has run

问题描述

I realise similar questions have been asked before but still dont understand what is happening with my code. I want to access the variable seq outside of the jQuery function after the user has inputed their sequence into the textarea. The console.log inside the jquesry function returns the inputed sequence but the console.log outside of the jQuery function(where I eventually want to put some other code to analyse the sequence) runs before the jquery function and returns an empty string. How can I make the code that uses the var seq only run after the submit button is clicked? Thanks!

var seq = "";

$("#subSeqType").on("click", function() {
  if ($("#proteinButton").is(":checked")) {
    $("#newTextArea").append("<textarea name = 'sequence' rows = '10' cols  = '80' placeholder = 'Enter Protein Sequence here' > < /textarea><br>");
  }
  if ($("#dnaButton").is(":checked")) {
    $("#newTextArea").append("<textarea name = 'sequence' rows = '10' cols  = '80' placeholder = 'Enter DNA Sequence here' > < /textarea><br>");
  }
  $("#subSeqType").remove();
  $("#newTextArea").append("<input id = 'subSeq' type='Submit'>");

  $("#subSeq").on("click", function() {
    seq = $("textarea:input[name=sequence]").val();
    console.log(seq);
  });
});

console.log("The sequence " + seq);

标签: javascriptjquery

解决方案


我将尝试解释这一点,但您应该阅读一些关于代码如何工作和运行的信息。

让我们声明代码语句的类型:

  1. 运行时代码

运行时代码是浏览器加载时运行的每一行代码

  1. 调用代码时运行

调用时运行代码是事件发生后将运行的代码。

统一这个概念:

创建侦听器时,创建该侦听器的规则是运行时代码。但是该侦听器中的代码只会在被调用时运行。


我在下面做了一个小例子,你的问题不是在改变变量,而是在你打印的时候。

打印机按钮将打印 var 值 cahnge calue 将更改该值一次

希望这可以帮助 :)

let myVar = "before";

console.log(myVar);

function myFun(){
  myVar = 'after';
}

function printer(){
  console.log(myVar);
}

console.log(myVar);
<button onclick="myFun()">change value</button>

<button onclick="printer()">print</button>


推荐阅读