JQuery 值未保存

JQuery value not saving?

本文关键字:保存 JQuery      更新时间:2023-09-26

单击它时我有两个div,它将ID值保存到变量中,该值正在保存到变量中,但在运行其他函数时未定义。

请看一下它应该更有意义.

链接

//Setting the click amount
var ClickedAmount = 1
    //On a note click run...
$(".note").click(function() {
    //If Click amount == 2 run
    if (ClickedAmount == 2) {
        //Alert NoteOne - This should be a value
        alert(NoteOne);
    };
    //If Click amount is == 1 run
    if (ClickedAmount == 1) {
        //Get the ID of the element that was clicked on and
        //replace note id with nothing.
        var NoteClicked = this.id.replace('note', '');
        //NoteOne - Now == the Divs number id Selected. 
        var NoteOne = NoteClicked
        alert(NoteOne);
        //Clicked amount added so other if statements runs on next click
        ClickedAmount++;
    };
})  

有什么建议吗?

在这里你可以找到一个工作的小提琴。

NoteOne 变量是函数中的局部变量。函数执行结束后,变量将被遗忘。如果要保留该值,请将变量设为全局变量。

var NoteOne = null;
//Setting the click amount
var ClickedAmount = 1
    //On a note click run...
$(".note").click(function() {
    //If Click amount == 2 run
    if (ClickedAmount == 2) {
        //Alert NoteOne - This should be a value
        alert(NoteOne);
    };
    //If Click amount is == 1 run
    if (ClickedAmount == 1) {
        //Get the ID of the element that was clicked on and
        //replace note id with nothing.
        var NoteClicked = this.id.replace('note', '');
        //NoteOne - Now == the Divs number id Selected. 
        NoteOne = NoteClicked
        alert(NoteOne);
        //Clicked amount added so other if statements runs on next click
        ClickedAmount++;
    };
})  

变量NoteOne将被提升到顶部。因此,它显示未定义。如果要使其按照预期工作,请将该NoteOne变量声明移到事件侦听器之外。换句话说,将其移动到该事件侦听器的词法范围。

var NoteOne;
var ClickedAmount = 1
$(".note").click(function() {
.
.

演示

你应该在函数之外声明NoteOne

//Setting the click amount
var ClickedAmount = 1
var NoteOne;
//On a note click run...
$(".note").click(function() {
  //If Click amount == 2 run
  if (ClickedAmount == 2) {
    //Alert NoteOne - This should be a value
    alert(NoteOne);
  };
  //If Click amount is == 1 run
  if (ClickedAmount == 1) {
    //Get the ID of the element that was clicked on and
    //replace note id with nothing.
    var NoteClicked = this.id.replace('note', '');
    //NoteOne - Now == the Divs number id Selected. 
    NoteOne = NoteClicked
    alert(NoteOne);
    //Clicked amount added so other if statements runs on next click
    ClickedAmount++;
  };
})
.note {
  width: 200px;
  height: 50px;
  margin-left: 5px;
  margin-top: 50px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
  <div id="note1" class="note">Note 1</div>
  <div id="note2" class="note">Note 2</div>
  <!-- The input section, user clicks this to login on. -->
  <input id="submit" name="submit" type="submit" value="Login">
</form>