简体   繁体   English

JavaScript:变量的动态值未更新。 为什么会这样呢?

[英]JavaScript: Dynamic value of a variable isn't being updated. Why is that happenning?

I recently started learning JavaScript and jQuery and I might be stuck on a newbie error. 我最近开始学习JavaScript和jQuery,可能会遇到新手错误。 I'm trying to keep my code as easy to read as possible, so I decided to store a chunk of HTML concatenated with a variable inside another variable. 我试图使代码尽可能易于阅读,因此我决定将与一个变量串联的HTML块存储在另一个变量中。 The concatenated variable holds a numeric value that gets updated every time I use the variable that holds everything, the html, and the other variable. 串联变量包含一个数值,每次使用包含所有内容的变量,html和其他变量时,该数值都会更新。

Something like this: 像这样:

var variableA  = 1;
var variableB = "<h4>Header number : "+ variableA +"</h4>";

var addHeader = funtcion(){
  $('#mainDiv').prepend(variableB);
  variableA++;
};

Whenever I call that function later in the code it always prints "Header number 1", what can I make it print the correct/desired values? 每当以后在代码中调用该函数时,它始终打印“ Header number 1”,那么我该如何打印正确/期望的值?

Header number 1 标头编号1

Header number 2 标头编号2

Header number 3 标头编号3

After you store variableB for the 1st time it is a string, and updating variableA won't update it. 第一次存储变量B后,它是一个字符串,更新变量A不会更新它。 To solve the problem, generate variableB whenever you call the function: 要解决此问题,请在每次调用函数时生成variableB:

var variableA  = 1;

var addHeader = funtcion(){
  var variableB = "<h4>Header number : "+ variableA +"</h4>";
  $('#mainDiv').prepend(variableB);
  variableA++;
};

If you want it to iterate each time you call it, you could try this: 如果您希望它在每次调用时都进行迭代,则可以尝试以下操作:

var headerIndex = 1;
var addHeader = function(){
  $('#mainDiv').prepend("<h4>Header number: " + (headerIndex++) + "</h4>");
};

Example: http://codepen.io/anon/pen/OyJpQq 示例: http//codepen.io/anon/pen/OyJpQq

You might want to use $('#mainDiv').html(...) instead of prepend(...) to get it to update the contents of the div entirely... 您可能要使用$('#mainDiv').html(...)而不是prepend(...)来使其完全更新div的内容...

The problem is variableB is String. 问题是variableB是String。 It isn't a reference so use var variableB = "<h4>Header number : "+ variableA +"</h4>"; 它不是参考,因此请使用var variableB = "<h4>Header number : "+ variableA +"</h4>"; inside your function to create new string every function invocation 在函数内部,以在每次函数调用时创建新的字符串

Move your variables inside the function, like so: 将变量移动到函数内部,如下所示:

var variableA  = 1;
var variableB = "<h4>Header will be replaced</h4>";

$('#mainDiv').html(variableB);  

$('#button').click(function(){ 
    addHeader();
});

function addHeader(){
  variableB = "<h4>Header number : "+ variableA +"</h4>";
  $('#mainDiv').html(variableB);
  variableA++;
}

And the HTML: 和HTML:

<div id="mainDiv"> </div>
<button id="button">clicky</button>

Play around with it here: 在这里玩:
http://jsfiddle.net/66rgnd0k/ http://jsfiddle.net/66rgnd0k/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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