2013-11-15 30 views
0

我的HTML:Jquery僅輸出選定的html,但不輸出它的子項?

<ul id="seasonsDropDown"> 
    <li>FALL 2013 HAUTE COUTURE 
    <ul class="designers"> 
     <li>Alexander Wang</li> 
     <li>BCBG MAX Azria</li> 
     <li>Diane con Fursternberg</li> 
     <li>Diane Von De</li> 
    </ul> 
    </li> 
    <li>SPRING 2013 HAUTE COUTURE</li> 
    <li>SPRING 2033 HAUTE COUTURE</li> 
    <li>SPRING 2093 COUTURE</li> 

什麼jQuery的方法,我應該使用,如果我只是想選擇/輸出字:

"FALL 2013 HAUTE COUTURE" 

不是UL名單?

現在如果我使用:

console.log($("#seasonsDropDown").html()); 

它會給我一切,包括HTML。

+2

它看起來像這個問題是一個重複:http://stackoverflow.com/questions/3442394/jquery-使用文本檢索只有文本沒有嵌套在子標籤 –

+2

請參閱$('#seasonsDropDown li:first')。contents()。filter(function(){ return this.nodeType == 3 })。text()'like http://jsfiddle.net/arunpjohny/y4D25/1/ –

回答

1

試試這個我沒有檢查它,但..

$(function() { 
    $('#seasonsDropDown').each(function(i, items_list){ 
     var myText = ""; 

     $(items_list).find('li').each(function(j, li){ 
      alert(li.text()); 
     }) 

     alert(myText); 

    }); 
}; 
0

jQuery將爲了知道要選擇哪一個項目需要一個選擇。最好的辦法是添加這樣的選擇:

$("#seasonsDropDown li").click(function(){ 
    $(this).addClass("selected"); 
}); 

之後,你就可以選擇它作爲如下:

console.log($("#seasonsDropDown .active").html()); 

如果你只是需要一個onClick事件,你可以做如下:

$("#seasonsDropDown li").click(function(){ 
    console.log($(this).html()); 
}); 
1
$("#seasonsDropDown li").html().substr(0,$("#seasonsDropDown li").html().indexOf('<')); 
1
console.log(
    $('#seasonsDropDown li:first').contents()[0] 
); 

你可能需要修剪返回的字符串。

1

你的問題與此類似question

jQuery的方法如下

$("li:eq(0)").clone().children().remove().end().text()