由于几个堆栈溢出参与者的宝贵援助附加内容的清单,我非常接近理想的效果......这里有一个回顾和更新,为利益相关方:使用复选框
我有一个系列产品模块,其中每个产品模块都包含产品名称和“比较”复选框。我的目标是在复选框被选中时在页面的其他区域生成选定产品的列表。由于必须有一个函数来检查最少两个,以及一些任意的最大值 - 作为复选框的一部分.click函数(根据Brian的版本,再次感谢您的宝贵帮助)或提交(我是倾向)。无论哪种情况,列表中的项目数量显然都是错误计数的; w /零或一个复选框选中,我正确地得到一个不足项目的警报;但是,如果我取消选中并重新检查几次,我的代码报告列表中的项目数量不正确。
为了简洁起见(!),我会放弃发布这两个版本,因为我在两个版本中都遇到类似的怪异现象。这是我最近的拼凑 - 很多人提前感谢任何见解。
<div class="product-module">
<div class="product-pic">
<div class="checkbox-wrapper">
<label for="compare1">
<input type="checkbox" class="checkbox" name="compare" id="compare1" />
Compare
</label>
</div>
</div>
<div class="product-info">
<p>
<a href="#" title="#"><span class="product-name">Product Name here</span></a><br />
</p>
</div>
<div class="compare">
<ul>
</ul>
<p class="error" style="display: none;">ACK! You've selected more than 4 products to compare.</p>
<p class="compare-button"><button type="submit">Compare</button></p>
<p class="clear-selections"><a class="button" id="clear-selections" href="#">Clear Selections</a></p>
<script type="text/javascript">
$(function(){
$('input[type="checkbox"]').attr('checked', false);
});
$(function(){
$('input[type="checkbox"]').click(function(){
var title = $(this).closest('.product-module').find('.product-name').html();
// as user checks the checkbox, add the item to the ul
if($(this).attr('checked')){
var html = '<li><a href="'+title+'">' + title + '</a></li>';
$('.compare ul').append(html);
} else {
// if user is un-checking the checkbox, remove the item from the ul
// orig: $('li[title="' + title + '"]').remove();
$('li a[href="' + title + '"]').remove();
}
});
});
$(function(){
$('.clear-selections').click(function(){
$('.compare ul').empty();
$('input[type="checkbox"]').attr('checked', false);
})
});
$(function(){
$('.compare button').click(function(){
minRequests = 2;
maxRequests = 4;
requested = $('.compare ul li').size(); // go figure: why not .length()?
if(requested < 2) {
alert ('Compare ' + requested + ' products?');
} else if((requested >= 2) && (requested <= 5)) {
alert ('There are ' + requested + ' products to compare');
} else {
alert (requested + ' is too many');
}
});
});
你意识到在你的jQuery中你正在寻找'.product-module',它似乎不存在于你提供的html中? – 2010-10-01 01:34:17
当您试图在您的问题中提供代码块时,您可以将每行代码缩进四个空格; **或**选择您想要显示为代码的所有文本,并* *单击文本区域上方的'101010'或*点击ctrl + K.对于内嵌代码,只需在任一侧使用反引号即可。请阅读[Markdown编辑帮助](http://stackoverflow.com/editing-help)。 – 2010-10-01 01:43:42
Thx指出这一点;这仅仅是因为我为了这个问题的目的而修改了课程,因为我成功地定位了产品名称 – shecky 2010-10-01 01:44:01