简体   繁体   English

了解函数如何使用和存储变量

[英]Understanding how functions use and store variables

My apologies is this has been asked/answered elsewhere.我很抱歉,这已在其他地方被问到/回答过。 I may not know the correct terminology to find the desired results.我可能不知道找到所需结果的正确术语。

I'm building a sort of web app and in one area a user clicks a button, where a variable is obtained from the number at the end of the button's ID and is then passed to other functions for use in further processing.我正在构建一种 web 应用程序,在一个区域中,用户单击一个按钮,其中从按钮 ID 末尾的数字获取变量,然后传递给其他函数以用于进一步处理。 The issue I'm running into is that each subsequent time similar buttons are clicked, the variables from prior clicks are still stored within those functions.我遇到的问题是每次单击类似按钮时,先前单击的变量仍存储在这些函数中。

JavaScript is not my forte, so I built a small fiddle that demonstrates my issue on a much smaller scale. JavaScript 不是我的强项,所以我建立了一个小小提琴,以更小的规模展示我的问题。 If you click "Submit 1" in the fiddle, then click ALERT CUST_NUM, an alert box will display the variable's value.如果您单击小提琴中的“提交 1”,然后单击 ALERT CUST_NUM,则会出现一个警告框,显示变量的值。 But if you repeat that process with either Submit 1 or Submit 2 (then clicking the ALERT button again), rather than alert a single instance of the variable, it will show multiple alert boxes in turn.但是,如果您使用 Submit 1 或 Submit 2 重复该过程(然后再次单击 ALERT 按钮),而不是警告变量的单个实例,它将依次显示多个警告框。 And so on if you click Submit 1, then ALERT CUST_NUM, then Submit2, etc, such that it'll alert the chain of variables in a series of windows.依此类推,如果您单击 Submit 1,然后单击 ALERT CUST_NUM,然后单击 Submit2 等,它会警告一系列 windows 中的变量链。 I was hoping someone might explain why this occurs, as I would have expected only a single instance of the variable to exist within the function, being overwritten each time.我希望有人能解释为什么会发生这种情况,因为我预计 function 中只存在一个变量实例,每次都会被覆盖。

 $(".submit-btn1").click(function() { var cust_num = parseInt(this.id.replace('test-button-', ''), 10); testFunction(cust_num); }) $(".submit-btn2").click(function() { var cust_num = parseInt(this.id.replace('test-button-', ''), 10); testFunction(cust_num); }) function testFunction(cust_num) { $("#alert-btn").click(function() { alert(cust_num); }) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="submit-btn1" id="test-button-1"> Submit 1 </button> <br/> <button class="submit-btn2" id="test-button-2"> Submit 2 </button> <br/> <button id="alert-btn"> ALERT CUST_NUM </button>

Every time you click on submit-btn1 or submit-btn2 , you are adding a new event handler with cust_num baked in to alert-btn .每次单击submit-btn1submit-btn2时,都会添加一个新的事件处理程序, cust_num烘焙到alert-btn中。 If you cleared the previous event handlers like in the following:如果您清除了以前的事件处理程序,如下所示:

function testFunction(cust_num) {
    $("#alert-btn").off(); 
    $("#alert-btn").click(function(){ 
    alert(cust_num);
  })
}

Then you would have only one event handler.那么您将只有一个事件处理程序。


A better approach would be to create a single event handler for alert-btn like so:更好的方法是为alert-btn创建一个事件处理程序,如下所示:

 var cust_num = 0; $(document).ready(function() { $(".mybuttons").click(function(){ cust_num = parseInt(this.id.replace('test-button-',''), 10); }) $("#alert-btn").click(function(){ alert(cust_num); }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="mybuttons" id="test-button-1">Submit 1</button> <br/> <button class="mybuttons" id="test-button-2">Submit 2</button> <br/> <button id="alert-btn">ALERT CUST_NUM</button>

I'd prefer a single handler for the input buttons that extracts the id and replaces the output button handler...我更喜欢用于提取 id 并替换 output 按钮处理程序的输入按钮的单个处理程序...

 $("#test-button-1, #test-button-2").click(function() { const alertWith = +(this.id.match(/\d+$/)[0]); // digits at end of a string $("#alert-btn").off('click').on('click', () => alert(alertWith)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="submit-btn1" id="test-button-1"> Submit 1 </button> <br/> <button class="submit-btn2" id="test-button-2"> Submit 2 </button> <br/> <button id="alert-btn"> ALERT CUST_NUM </button>

jdt's answer is spot on about what's happening with your code. jdt 的答案是关于您的代码发生了什么。

What is duplicated, as already explained, are the listeners attached to the click event, each with its instance of testFunction .如前所述,重复的是附加到 click 事件的侦听器,每个侦听器都有其testFunction实例。 Actually each time testFunction is called, there exists a single instance of test_num , as expected.实际上,每次调用testFunction时,都存在一个test_num实例,正如预期的那样。

I don't like to skin cats;) and yet我不喜欢给猫剥皮;)然而

There are more things in heaven and earth, Horatio, Than are dreamt of in your philosophy...天地间有更多的东西,霍拉旭,比你的哲学所梦想的还要多……

JQuery is a beautiful library, it offers many ways to approach this simple puzzle. JQuery 是一个漂亮的库,它提供了许多方法来解决这个简单的难题。 One particular function that IMHO deserves attention is .data() link to official documentation恕我直言,值得关注的一个特别 function 是官方文档.data()链接

It allows to:它允许:

  • extract values from data attributes of an html tag从 html 标签的数据属性中提取值
  • attach data to a dom element将数据附加到 dom 元素

In this situation, with minor changes to the html, these functionalities could be used to carry the number for each number button, and to attach it directly to the alert button.在这种情况下,只需对 html 进行细微更改,即可使用这些功能为每个数字按钮携带数字,并将其直接附加到警报按钮。

 // listen for click event on any button with an id // that begins with 'test-button' $("button[id^='test-button']").click(function() { // take the value from the attribute of the clicked // element and assign it to the alert button $("#alert-btn").data("lastSelectedNum", $(this).data().num) }) $("#alert-btn").click( function() { // the alert will display the value assigned // or 'unset' if it's undefined alert( $(this).data().lastSelectedNum?? "unset") });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="test-button-1" data-num=1> Submit 1 </button> <br/> <button id="test-button-2" data-num=2> Submit 2 </button> <br/> <button id="alert-btn"> ALERT CUST_NUM </button>

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

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