我刚刚开始使用JQuery,我需要更改两个元素的css类并删除它们的onclick事件处理程序。
当点击具有类upDown的div中的三个元素中的任何一个时,会出现一个弹出窗口。单击该弹出窗口中的按钮时,将调用vote_click()。
我需要禁用“up”和“down”类的元素,但不能禁用其他元素。
<div class="upDown">
<div class="up" id="ctl04_btnUp" onclick="lastClick=this;" ></div>
<div class="com" id="ctl04_btnCom" onclick="lastClick=this;"></div>
<div class="down" id="ctl04_btnDown" onclick="lastClick=this;"></div>
</div>
这是我的尝试
var lastClick; //will be set to either the "up" or "down"
function vote_click() {
if (lastClick && lastClick.className != "com") {
$("#"+lastClick.parentElement.id + " > .up .down").each(
function(index, e) {
alert('disabled ' + this.id);
this.onclick = null;
this.className += '-ya';
}
);
lastClick = null;
}
}
我显然不知道我在做什么,所以对我的方法的任何一般性观察都会受到赞赏。
答案 0 :(得分:1)
我希望以下代码符合您的要求:
(function($) {
var lastClick = null;
$('div.upDown .up, div.upDown.com, div.upDown.down').bind('click', function(e) {
lastClick = this;
});
function vote_click() {
if (lastClick && (lastClick.hasClass('up') || lastClick.hasClass('down')) {
$('div.upDown .up, div.upDown.down').each( function() {
var $this = $(this);
$this.unbind('click');
var c = $this.attr('class');
$this.removeClass(c).addClass(c + '-ya');
});
}
}
})(jQuery);
注意:
onclick
属性,因此您的JS纯属不引人注目。lastClick
变量是全局的。$("#"+lastClick.parentElement.id + " > .up .down")
会选择类down
的所有元素,这些元素是类up
的元素的后代,该元素是ID为lastClick.parentElement.id
的元素的子元素。那不是你想要的。您可以更轻松地写出您想要的内容$(lastClick).parent().find('.up, .down')
。 修改强>
关于为什么onclick
通常不受欢迎的一句话:就个人而言,我不喜欢JavaScript中的全局变量,因为页面中运行的所有JS代码(可能来自几个不通信的开发人员)共享一个全局命名空间。通过onclick
等方式声明的事件处理程序通常引用全局变量(就像你的情况一样),所以这是我避免它们的一个原因。
第二个是onclick
属性中指定的代码在特殊范围(或范围链,确切地说)中运行。它直接在全局命名空间中运行不,但在由
document
对象window
)这可能会导致意外的误解,例如您致电open()
并表示window.open()
,但您获得的是document.open()
。简而言之,我更喜欢确切知道我的事件处理程序能够和不能看到的内容,我认为在更大的项目中,严格分离代码部分和避免全局变量会得到回报。对于较小的代码段,只要您不在onclick
属性中编写小说,使用onclick
等就可以了。
P.S。:是的,很明显,我正在使用Flanagan的“JavaScript - The Definitive Guide”中的一个例子。