Jquery帮助函数与复选框foreach
问题描述:
我有几个复选框,我试图从使用jQuery帮助函数获取值。Jquery帮助函数与复选框foreach
<div class="checkbox">
<label>
<input name="gift_wrap" value="Wrap" type="checkbox"> Gift wrap
</label>
<label>
<input name="gift_wrap" value="Wrapper" type="checkbox"> Wrapper
</label>
<label>
<input name="gift_wrap" value="Pap" type="checkbox"> Pap
</label>
</div>
这里是Jquery的:
_getContent: function (elm) {
if(elm.is(":checkbox, :radio")){
return elm.is(":checked") ? elm.map(function(){
return $(this).val()}) : '';
} else {
return elm.text();
}
return '';
}
这是它如何被称为:
_getProductDetails: function (elm) {
var mi = this;
var p = {};
elm.parents(this.options.productContainerSelector)
.find(this.options.productElementSelector)
.each(function() {
if ($(this).is('[name]') === true || typeof $(this).data('name') !== typeof undefined) {
var key = $(this).attr('name') ? $(this).attr('name') : $(this).data('name');
var val = mi._getContent($(this));
if(key && val){
p[key] = val;
}
}
});
return p;
}
我得到这个[object Object]
而不是值。我并不擅长Jquery,也不完全知道如何去做,我也尝试过.each
,但没有取得太大的成功。
答
jQuery的.map()
方法返回函数结果的jQuery集合,而不是数组。您可以使用.get()
将其转换为数组。
但是,似乎没有理由首先拨打.map()
。只要返回元素的值,如果它被检查。
_getContent: function (elm) {
if(elm.is(":checkbox, :radio")){
return elm.is(":checked") ? elm.val() : '';
} else {
return elm.text();
}
}
答
.map
是要在数组上调用的函数。我会假设你正在通过一个输入。这将工作(修改,使其工作在片段)
此外,最后的回报将永远不会触发。所以这里有一个解决方案:
_getContent= function (elm) {
if(elm.is(":checkbox, :radio")){
return elm.is(":checked") ? elm.val() : '';
}
return elm.text();
}
console.log(_getContent($('input').eq(1)))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label>
<input name="gift_wrap" value="Wrap" type="checkbox"> Gift wrap
</label>
<label>
<input name="gift_wrap" value="Wrapper" type="checkbox" checked> Wrapper
</label>
<label>
<input name="gift_wrap" value="Pap" type="checkbox"> Pap
</label>
</div>
所以你想说如果一个复选框被选中,返回值? – Keith
你最近怎么打电话给帮手? – Barmar
@Barmar它附加使用{gift_wrap} –