javascript - 每个 selectedTest 都存在于 data-Test 数组中并获取结果
问题描述
HTML
<div class="col-test" data-test="Swimming pools|Fitness center|Parking|Washer|Spa|Parking|Clubhouse|Valet trash|Washer">
用户从下拉列表中选择了多个选项并获取值
var test = $('#options').val();
console.log(test); // Array [ "Swimming pools", "Fitness center" ]
这是伪代码
for each selectedTest data (from multiselect input)
check if it exists in the data-test array
if it does not exists:
then show = false
otherwise:
do nothing and continue to check the next selectedTest (no code is needed here)
下面的代码有问题。我需要确保每个 selectedTest 都存在于 data-Test 数组中。它没有按预期返回结果。代码有问题。
data-test="Swimming pools|Fitness center|Parking|Washer|Spa|Parking|Clubhouse|Valet trash|Washer"
var $variable = $('.col-test');
if(test && test != null && test.length > 0) {
console.log($varible.data('test'));
var arryTest = $varible.data('test').split("|");
arryTest.forEach((singleTest) => {
if(!test.includes(singleTest)){
show = false;
}else{
//do nothing and continue to check the next selected Amenity
}
});
}
我可以在控制台中看到一遍又一遍地打印数据测试结果。我认为循环不起作用。
结果
游泳池|健身中心|停车场|洗衣机|水疗中心|停车场|会所|代客垃圾|洗衣机
游泳池|健身中心|停车场|洗衣机|水疗|停车场|会所|代客垃圾|洗衣机|游泳池|健身中心|停车场|洗衣机|水疗|停车场|会所|代客垃圾|洗衣机
游泳池|健身中心|停车场|洗衣机|水疗中心|停车场|会所|代客垃圾|洗衣机|游泳池|健身中心|停车场|洗衣机|水疗|停车场|会所|代客垃圾|洗衣机|游泳池|健身中心|停车场|洗衣机|水疗中心|停车场|会所|代客垃圾|洗衣机
解决方案
考虑以下示例。
$(function() {
var dataTest = $("#col-test").val().split("|");
console.log(dataTest);
$("#user-options").append("<option>Item 1</option>");
$.each(dataTest, function() {
$("#user-options").append("<option>" + this + "</option>");
});
$("#user-options").append("<option>Last Item</option>");
$("#user-options").change(function() {
var show = true;
var options = $(this).val();
console.log("Selected Options", options);
$.each(options, function(i, o) {
if (dataTest.indexOf(o) == -1) {
show = show && false;
}
});
console.log(show);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="col-test" value="Swimming pools|Fitness center|Parking|Washer|Spa|Parking|Clubhouse|Valet trash|Washer" />
<select id="user-options" multiple>
</select>
当用户做出选择时,change
会触发一个事件。当有change
用户的选择时,将与选项列表进行比较。如果 Option 的索引为-1
,则它不存在于列表中,show
并将设置为 false。
我没有一套完整的选项,所以我必须根据我拥有的唯一数据构建一个列表,这意味着所有选择的选项都将在列表中,你会得到true
. 所以我添加了“第 1 项”和“最后一项”。如果选择其中任何一个,您将获得false
.
推荐阅读
- c# - 基于 Autofac 变量名的注入
- c# - 通过 C# 代码将参数传递给在 cmd 中运行的命令
- python - 没有 OpenFabrics 连接
- image - 看不懂SIFT关键点提取(非描述)算法
- html - 自动换行后缩小段落
- maxima - Maxima:如何替换变量以简化方程?
- xamarin - 为新的 Xamarin Forms 应用程序使用 .NET Standard 或使用共享库
- react-native - react native expo 项目中的 HTTPS 调用引发网络错误
- android - 查看寻呼机暂停/卡住
- c# - C# 命名参数的 F# 等价物是什么?