【发布时间】:2021-12-30 17:34:03
【问题描述】:
我遇到了一些问题,当我选择复选框时如何显示来自 ajax 的名称调用?
这是下面的图片,我的 ajax 被调用来为每个人创建一个复选框
现在我希望当我选择给定名称的任何复选框时,将显示在选定项下方: 如果我取消选中该复选框,则名称将消失,因为我正在使用 ajax 调用,我该怎么做?
这是我的html代码
<div class="container-body ">
<fieldset class="Field">
<ul id="checkbox" class="checkbox">
</fieldset>
</ul>
<div id="no-recyclable-records" >
<h4>No Recyclable Records Found</h4>
</div>
</div>
<div class="Select">
<p>Selected:</p>
<div id="divfilter"></div>
</div>
这是我用来创建复选框的 ajax 代码:
$.ajax( {
url: 'https://ecoexchange.dscloud.me:8090/api/get',
type: 'GET',
dataType: 'json',
headers:{
query: "RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
},
success: function(data) {
//console.log(data);
var html='';
$.each(data, function(key, value) {
var type = value.RecyclableType
//console.log(type)
html +='<li data-type="'+ type + '"><input type="checkbox" name="recyclable_id[]" value="'+value.RecyclableID+'"><label style="padding-left: 10px;">'+value.Name+'</label><br></li>';
//console.log(value)
});
$('#checkbox').html(html);
// Toggled it to success after loading all of the checkboxes
// This will hide the "No Recyclable Records" portion
toggleRecord("success");
}
});
我尝试使用 javascript 但没有显示名称
// find and retrieve all <input> elements of
// 'type=checkbox':
var checkboxes = $('input[type=checkbox]');
// use the on() method to bind the anonymous function
// as the event-handler of the 'change' event:
checkboxes.on('change', function(){
// update the '#divfilter' element's text:
$('#divfilter').text(function(){
// we return the following as the new text:
// first we filter the checkboxes collection to
// retain only those that match the ':checked'
// pseudo-class, and then create a map:
return checkboxes.filter(':checked').map(function(){
// the contents of the map are comprised of
// the 'name' property of each checked check-box:
return value.Name;
//return this.name;
// we convert the map() into an Array, using get():
}).get()
// and join the Array elements together with the
// supplied String, and finished with a period:
.join(', ') + '.';
});
});
【问题讨论】:
-
value中的value.Name是什么? -
这应该是我的价值。 name = 我的 ajax 名称
-
向
.map(function(){中的函数提供一个参数,例如.map(function(n){,并在匿名函数中访问n的属性 -
看起来您将
li元素直接附加到div没有合适的list父级,还是我错过了? -
我已经删掉了一些代码,因为代码是用于我的下拉列表的,当项目没有显示时,切换记录会打开
标签: javascript html jquery ajax