使用 JQuery 创建关联数组


Creating an Associative Array using JQuery

我正在尝试使用 JQuery 创建一个associative array。我希望它填充用户从UI中选择的复选框的值。

起初我像这样创建数组:

$contentArray = [];
$('.content-filter :checked').each(function(){
    $contentArray.push(this.value);
})

但问题是,当我通过Ajax将其传递给php脚本时,很难从中获取值。我宁愿能够根据与其关联的键从数组中获取值。

所以我决定将我的代码修改为:

$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter :checked').each(function(){
    $contentArray[this.value] = this.value;
})

但是现在当我执行console.log时,我被告知我的数组的内容不包含任何内容。

谁能建议我如何解决此问题并告诉我哪里出了问题?

你的过滤器是错误的 - 你需要在:checked之前删除空格,否则它会在复选框内查找一个被选中的元素,这显然不存在:

$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
    $contentArray[this.value] = this.value;
})
console.log($contentArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />

但是,如前所述,这只会创建一个碎片数组。如果你想要真正的关联键,你应该创建一个对象(我不认为这在 php 中更容易处理):

$contentObject = {}; //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
    $contentObject[this.value] = this.value;
})
console.log($contentObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />