2017-03-02 90 views
0

我有一個非常簡單的函數,我只想在選定的對象具有某種類型的子項時才工作 - 在這種情況下,如果它具有ul嵌套。如何判斷對象是否有某個元素的子元素?

我已經試過這一點:

var onMouseOver = function() { 
if (this.getElementsByTagName('ul') > 0);{ 
    console.log('entered'); 
} 
} 

這:

var onMouseOver = function() { 
if (this.querySelector('ul') != null);{ 
    console.log('enter'); 
} 
} 

,但它並不能幫助 - 功能仍會啓動,即使它returnes '空'。

回答

0

你應該看看這些選擇器的長度屬性。

var onMouseOver = function() { 
 
if (this.querySelectorAll('ul').length > 0);{ 
 
    console.log('enter'); 
 
} 
 
}

var onMouseOver = function() { 
 
if (this.getElementsByTagName('ul').length > 0);{ 
 
    console.log('entered'); 
 
} 
 
}

+0

我已經嘗試了這兩個版本,但它仍然無法工作。 例如:在html中我有元素嵌套[像這樣](http://pastebin.com/bKHPnvDb)。對於

  • 元素3
  • 函數應該不起作用,但它仍然有效。 – Lafioka

    0

    試試這個:)

    function ok(obj) { 
     
        var l = obj.children.length; 
     
    
     
        for (var i = 0; i <= l; i++) { 
     
        if (obj.children[i].tagName == "UL") { 
     
         var c = obj.children[i].children[0]; 
     
         alert("child id is :-" + c.tagName); 
     
         alert("child id is :-" + c.id); 
     
         alert("child value is :-" + c.innerHTML); 
     
         break; 
     
        } 
     
    
     
        } 
     
    }
    #child { 
     
        display: none; 
     
    }
    <!DOCTYPE html> 
     
    <html> 
     
    <body> 
     
        <div id="Parent" onmouseover="ok(this)">Find Child ? mouse over me 
     
        <p id="child">I'm Child</p> 
     
        <ul> 
     
         <li id="list">hello</li> 
     
         </ul> 
     
        </div> 
     
    </body> 
     
    </html>

    +0

    謝謝,但那不完全是我需要的 - 我正在尋找一些只能起作用的東西,如果孩子/孩子是某個標籤;這種情況下,我需要函數才能工作,只有有ul的嵌套。 – Lafioka

    +0

    我已更新檢查 –

    +0

    謝謝!這比我想象的要長一些,但是很有效。 :) – Lafioka

    相關問題