2009-01-25 92 views
0

我正在使用jQuery。如何有效提取列表數據?在jQuery中提取列表數據

列表有:

<li class="add"><a href="#">Data1</a></li> 
<li class="add"><a href="#">Data2</a> </li> 
... 

我的jQuery有:

$(".add").click(function(e){ 
    e.preventDefault(); 
    // Here is to get the value of Data1 and Data2... 
    // How do I alert Data1, Data2 effectively? 
}); 

回答

-1

或只是

$('li.add a').each(function() { 
    data.push($(this).text()); 
    }); 
1

你可以嘗試以下方法:

$('.add').click(function(e) { 
    e.preventDefault(); 

    // Initialize an array for all texts 
    var data = []; 

    // For each <li> with class 'add'... 
    $('li.add').each(function() { 
    // ...append the element's text to the data array 
    data.push($(this).text()); 
    }); 

    // Just for testing: Alert the array as a string 
    alert(data.join(',')); 
}); 
1

我會說:

$('.add').click(function(e){ 
e.preventDefault(); 
data = []; 
//loop over each li: 
$('li.add').each(function() { 
    //Get the a and the text contents of that 
    data.push($(this).find('a').text()); 
} 
alert(data.join(',')); 
} 

這是費迪南德答案的微小變化。

0

如果它的任何安慰,我做了這樣的事情最近的一個項目。我想把它放到可以搜索信息並突出顯示頁面中的文本的地方。但是我想對數據本身做這件事(這意味着不要每次都擊中HTML)。

http://www.ffin.com/onlinebankingfaq

如果你看看JavaScript代碼,你可以看到我是如何設置的數據,這可能會幫助你。