簡體   English   中英

如何在jQuery中獲取具有特定父類的所有元素的內容並將它們傳遞給GET變量?

[英]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 arr = [];
$('.list_array li').each(function() {
    var t = $(this).text();
    if (arr.indexOf(t) === -1) {
        arr.push(t)
    }
})
// arr = arr.join(',')  
// =>  item A,item B,item C,item D,item E

DEMO

您可以使用jQuery $.post$.ajax實用程序函數將數據發送到PHP:

  1. $。員額()
  2. $阿賈克斯()
  3. $獲得()

嘗試這個

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM