2016-08-14 42 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

謝謝!這是我正在尋找的。 –

相關問題