2016-08-14 111 views
1

我试图将鼠标悬停在一个元素上,检查该类是否包含前缀,如果是,请将一些样式应用到这个元素。这个问题是,如果我有一个名为“bluescript-contact-form”的类(注意前缀“bluescript-”),那么当我将鼠标悬停在子元素上时,不会触发这个div。这如何实现?检查一个父类是否有一个类,如果是这样应用样式到这个父

这是迄今为止我所编写的代码:

var controls = { 
    clickedElement: "", 
    prefixCheck: function(c){ 
    // classPrefix = "bluescript-" 
    return (c.indexOf(classPrefix) !== -1) ? true : false; 
    }, 
    bindUIActions: (function(){ 
    $(outputElement).on("load", function(){ 
     $(outputElement).contents().find("*").on("click", function(e){ 
     e.stopImmediatePropagation(); 
     }); 
     $(outputElement).contents().find("*").mouseenter(function(e){ 
     e.stopImmediatePropagation(); 
     if(typeof $(this).attr("class") !== "undefined"){ 
      /* This works, but only on the current element. 
      It does not check if a parent contains a class, 
      that contains a prefix that matches. */ 
      if(controls.prefixCheck($(this).attr("class"))){ 
      $(this).css({ 
       outline: onHoverBorder, 
       cursor: "pointer" 
      }); 
      } 
      /* Else if(a parent contains a class that matches, 
      apply style to THIS parent element) */ 
     } 
     }); 
     $(outputElement).contents().find("*").mouseleave(function(e){ 
     $(this).css({ 
      outline: "none", 
      cursor: "default" 
     }); 
     }); 
    }); 
    })() 

} 

我希望这是非常明显的。任何帮助,将不胜感激。谢谢!

回答

2

stopImmediatePropagation停止事件向上传播DOM树(它不会到达父级)。如果由于某种原因需要调用该方法,可以将父节点的类作为$(this).parent()。attr(“class”)。此代码应该很好地工作:

else if(controls.prefixCheck($(this).parent().attr("class"))){ 
    // Your code here 
} 

如果您需要更改其类的前缀开始,你应该使用父母()方法的所有祖先的风格,请参阅:

else{ 
    $(this).parents().each(function(index,value){ 
     if(controls.prefixCheck($(this).attr("class"))){ 
      $(this).css({ 
       outline: "none", 
       cursor: "default" 
      }); 
     } 
     // Uncomment the next line if you only want to change the first match found. 
     // return false ; 
    }); 
} 

您应该使用startsWith检查之类的前缀:

prefixCheck: function(c){ 
    // classPrefix = "bluescript-" 
    return c.startsWith(classPrefix); 
}, 

或使用indexOf正确:

prefixCheck: function(c){ 
    // classPrefix = "bluescript-" 
    return c.indexOf(classPrefix) === 0; 
}, 

否则,您可能会得到误报。

+0

这是否为每个父母爬行?还是只有一个?因为我想检查所有的父母。 –

+0

@GerritLuimstra不,它不。您可以使用parents()方法来实现此目的。我相应地更新了我的答案。 – 2016-08-15 17:56:52

+0

谢谢!这是我正在寻找的。 –

相关问题