JQuery 值不保存?

JQuery value not saving?

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

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

Link

//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++;
    };
})  

有什么建议吗?

在这里你可以找到 working fiddle.

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() {
.
.

DEMO

您应该在您的函数之外声明 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>