[英]How can I get an array of all elements within a specific class using javascript and/or jQuery?
[英]How can I get the contents of all elements with a specific parent class in jQuery and pass them in a GET variable?
我需要使用list_array
的父類收集所有列表項的內容,然后通過GET變量將它們傳遞給AJAX調用。 你能推薦一個策略嗎?
這是一個小提琴 。
HTML:
<div>
<ul class="list_array">
<li>item A</li>
<li>item B</li>
<li>item C</li>
</ul>
</div>
<p>some text</p>
<div>
<ul class="list_array">
<li>item B</li>
<li>item C</li>
<li>item D</li>
</ul>
</div>
<p>some text</p>
<div>
<ul class="list_array">
<li>item A</li>
<li>item C</li>
<li>item E</li>
</ul>
</div>
這是我目前的進展:
$(document).ready(function(){
var listItemArr = [];
$('.list_array li').each(function() {
listItemArr.push($(this).text());
});
alert(listItemArr);
});
正如小提琴所示,這不起作用。
理想情況下,我也會傳遞唯一的字符串,因此預期的結果將是:
item A
item B
item C
item D
item E
(並且不包含重復項)
此外,歡迎任何將數組傳遞給我的PHP處理頁面的建議。
謝謝!
不了解PHP。 這是客戶端代碼:
var arrayName = 'whatever';
//use an object as an SET to remove duplicated items
var dict = {};
$('.list_array li').map(function() {
return $(this).text();
}).each(function(){
dict[this] = '';
});
//retrieve the values saved to the SET
var params = '';
for(var k in dict)
params += arrayName + '=' + k +'&';
//send request
$.get('/path/to/your.php', params, function (response) {
console.log(response);
//or do what ever you want with the response.
}, 'html');
嘗試這個
var all=[];
$('ul.list_array li').each(function(){
var text=$(this).text();
if($.inArray(text, all)==-1) all.push(text);
});
$.get('/url/to/page', {'items': all}, function(data){
console.log(data);
});
變量all
是一個數組,如["item A", "item B", "item C", "item D", "item E"]
,你的數組在$_GET
可用$_GET['items']
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.