繁体   English   中英

jQuery为preventDefault选择元素

[英]jQuery selecting elements for preventDefault

$('input[name=boxes], .item_add a ').on('click', function(e) {
  e.preventDefault();
 //do stuff inherent to both 
}

当我单击链接[.item add a] ,是否有办法防止滚动的默认动作,但仍保持选中和取消选中复选框input[name=boxes]的默认动作input[name=boxes]而不会将这两者分解为单独的onclick函数?

$('input[name=boxes], .item_add a ').on('click', function(e) {
   this.tagName == 'A' && e.preventDefault();
   //do stuff inherent to both 
}
$('input[name=boxes], .item_add a ').on('click', function(e) {
     if($(e.target).is('a')) e.preventDefault(); //if it is a link then prevent

     //do stuff inherent to both 
})

检查目标元素

if($(this).is('.item_add a')) e.preventDefault();
$('input[name=boxes], .item_add a ').on('click', function(e) {
  if (this.tagName == "A"){
    e.preventDefault();
  }

//do stuff inherent to both 
}

您可以将其保留在一个函数中,但是可以在函数内部进行检查吗?

if(!$(this).is(':checkbox')) {
   e.preventDefault();
   return false;
}

尝试这个:

$('input[name=boxes], .item_add a ').on('click', function(e) {
    if (!$(this).is(':checkbox') {
        e.preventDefault();
    }

    //do stuff inherent to both 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM