Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery问题的帮助_Jquery - Fatal编程技术网

jQuery问题的帮助

jQuery问题的帮助,jquery,Jquery,我有一个简单的页面,上面有一个项目列表。我允许用户对这些项目进行投票,但我只想允许用户每年投票一次。项目 我制作了一个jQuery脚本,将一个类添加到用户投票的项目中: if(!$(this).find(".item span").hasClass("voted")) { $(".item").hover(function() { $(this).find(".ratingbar").hide(); $(this).find(".votebar").show(); },

我有一个简单的页面,上面有一个项目列表。我允许用户对这些项目进行投票,但我只想允许用户每年投票一次。项目

我制作了一个jQuery脚本,将一个类添加到用户投票的项目中:

if(!$(this).find(".item span").hasClass("voted")) {
  $(".item").hover(function() {
    $(this).find(".ratingbar").hide();
    $(this).find(".votebar").show();
  }, function() {
    $(this).find(".votebar").hide();
    $(this).find(".ratingbar").show();
  });
};
这是防止用户对同一项目再次投票的脚本

$(".votebutton").click(function() {
  $("div#"+offerid).find(".item").addClass("voted");
});
这不管用。悬停项目时,即使第二个脚本成功地将类“投票”添加到html中,悬停函数仍会运行

为什么会这样?

您需要使用(或)来防止这种情况发生,因为它附加到DOM元素,所以它的类更改不会解除那些
mousenter
mouseleave
事件处理程序的绑定(这就是hover实际绑定到的对象)

但是,当您悬停时,将计算类是否匹配(因为它会关闭事件冒泡,所以它会在执行之前检查选择器是否匹配),并将执行您想要的操作,如下所示:

$(".item:not(.voted)").live('mouseenter', function() {
  $(this).find(".ratingbar").hide();
  $(this).find(".votebar").show();
}).live('mouseleave', function() {
  $(this).find(".votebar").hide();
  $(this).find(".ratingbar").show();
});
没有理由执行
if
语句,这将适用于所有元素,您应该只运行一次。以前,它检查当前项是否有投票的
类…但随后将鼠标悬停应用于所有
.item
n
次数)元素,而不是在您现在所在的任何循环之外运行一次,它应该直接位于
文档中。ready
处理程序

编辑:您也可以将其缩短,因为您只需切换元素,使用,效果相同,只是更简单/更简洁:

$(".item:not(.voted)").live('mouseenter mouseleave', function() {
  $(".ratingbar, .votebar", this).toggle();
});

您稍后将在代码中添加类
voated
,但您的
.hover()
已将事件
mouseenter
mouseleave
绑定到

如果要阻止事件处理程序在元素具有
投票
类时继续,可以检查该类并从事件处理程序提前返回:

$(".item").hover(function() {
  // save this variable so we don't need to call $() three times
  var $this = $(this);
  // stop processing the event if the item has the 'voted' class
  if ($this.is('.voted')) return; 

  $this.find(".ratingbar").hide();
  $this.find(".votebar").show();
}, function() {
  var $this = $(this);
  // note - you might still want to process this event as they mouse out after voting?
  if ($this.is('.voted')) return; 

  $this.find(".votebar").hide();
  $this.find(".ratingbar").show();
});
投票后,您可以删除事件处理程序:

$(".votebutton").click(function() {
  $("div#"+offerid).find(".item").addClass("voted").unbind('mouseenter mouseleave');
});

非常感谢你!在升级到jQuery1.4之后,它工作得非常好:-)