我的问题是data-list
compare
类是动态生成的,我在compare
div上实现了点击处理程序。
在每次单击时,只有data-list
数组发生更改,因此我无法确定如何在每次单击时获取更新的数据列表值。
我知道委托活动,但无法弄清楚如何在这里使用:
$('.compare').on('click','what-to-put-here?',function (e) {
var data = $(this).data('list');
alert(data);
});
<div class="compare" id = "compare-box" data-list = "">
<div class = "a" style="margin-bottom: 5px;padding: 0px;font-size:13px">
<h4>Compare Results (<span id="compare-items"></span>)</h4>
</div>
</div>
JSFiddle Guys Check My Code
答案 0 :(得分:1)
我已经改变了你的小提琴,希望它会有所帮助:)
var count = 0
var list = $("#compare-box").attr('data-list');
if(list)
{
list = JSON.parse(list);
}
else
{
list = [];
}
$(".compare-result").on('click',function(){
//var list =
if($(this).is(":checked"))
{
if(count < 4)
{
var id = $(this).val();
list.push(id);
count++;
}
else
{
event.preventDefault();
$('input.compare-result').not(':checked').attr("disabled",true);
alert('you can only compare 4 items');
}
}
else
{
var id = $(this).val();
count--;
if(count < 4)
{
var index = list.indexOf(id);
if (index > -1) {
list.splice(index, 1);
}
$('input.compare-result').not(':checked').attr("disabled",false);
}
else
{
alert('error');
}
}
selectedList = JSON.stringify(list);
$("#compare-items").html(count);
console.log(selectedList);
});
//Main Problem Starts
$('.compare').on('click',function (e) {
var data2 = '';
$(".compare-result:checked").each(function(){
data2 += $(this).val()+",";
});
data2 = data2.substring(0,data2.lastIndexOf(","));
alert(data2);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="compare-result" value = "1">a
<input type="checkbox" class="compare-result" value = "2">b
<input type="checkbox" class="compare-result" value = "3">c
<input type="checkbox" class="compare-result" value = "4">d
<input type="checkbox" class="compare-result" value = "5">e
<div class="compare" id = "compare-box" data-list = "">
<div class = "a" style="margin-bottom: 5px;padding: 0px;font-size:13px">
<h4>Compare Results (<span id="compare-items"></span>)</h4>
</div>
</div>
&#13;
答案 1 :(得分:0)
遵循以下语法
jQuery(document.body).on('click', '.compare', function(){
alert('what ever you want to do here');
return false;
});
答案 2 :(得分:0)
您需要将代码包装在document.ready
处理程序中,以确保在附加事件处理程序时将元素全部加载到DOM中。如果它在一个单独的文件中并不重要,您仍然可以使用处理程序:
$(document).ready(function () {
$('.compare').on('click','what-to-put-here?',function (e) {
var data = $(this).data('list');
alert(data);
});
});
答案 3 :(得分:0)
设置数据时,需要使用
$(selector).data("name", value)
而不是$(selector).attr("data-name", value)