【发布时间】:2014-05-26 15:49:31
【问题描述】:
我正在构建一个 Web 应用程序,并且正在学习中。
这是我发布的第一个问题。
我创建了一系列 SPAN 元素,其行为类似于按钮。
单击一个元素(橙色元素)后,我想通过更改其类(因此将其颜色更改为灰色)来有效地禁用它。
.on("click) 之前的萤火虫:
<span class="sample_but3 sample_butOrange">3</span>
.on("click") 之后的萤火虫:
<span class="sample_but3 sample_butGrey">3</span>
我可以看到,使用萤火虫,类“.sample_butOrange”被删除,而类“.sample_butGrey”完全按照我的预期添加。 但它的下一点让我难住了。
现在,如果我单击灰色按钮(最初是橙色),我仍然会收到我按下橙色按钮的警报,而不是收到我按下灰色按钮的警报。
注意:我已经设置了通知哪个按钮被按下的警报。
有人可以向我解释发生了什么吗?
以完整代码为例:
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="sample_button.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
// Grey button means do nothing.
function sample_processGrey() {
alert("You pressed the grey button. Don't do anything as this button is disabled.");
}
function sample_processOrange() {
alert("You pressed the orange button");
$(".sample_but3").addClass("sample_butGrey").removeClass("sample_butOrange");
}
$(document).ready(function () {
// Do something when the buttons are pressed.
$(".sample_butGrey").on("click", sample_processGrey);
$(".sample_butOrange").on("click", sample_processOrange);
});
</script>
</head>
<body>
<span class="sample_but1 sample_butPurple">1</span>
<span class="sample_but2 sample_butGreen">2</span>
<span class="sample_but3 sample_butOrange">3</span>
<span class="sample_but4 sample_butRed">4</span>
<span class="sample_but5 sample_butBlue">5</span>
</body>
</html>
【问题讨论】:
-
线索:事件委托
标签: javascript jquery class button jquery-selectors