点击它时我有两个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++;
};
})
有什么建议吗?
答案 0 :(得分:1)
您可以在这里找到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++;
};
})
答案 1 :(得分:0)
变量NoteOne
将被提升到顶部。结果它显示未定义。如果你想让它按照你的期望工作,那么将NoteOne
变量声明移到事件监听器之外。换句话说,将其移动到该事件监听器的词法范围。
var NoteOne;
var ClickedAmount = 1
$(".note").click(function() {
.
.
答案 2 :(得分:0)
您应该在功能之外声明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>
&#13;