On Div中的多个单击事件返回为一次单击



我有点为难。我有好几张卡……有几个点击事件可能(7),以准确地在每个卡内。

我为它们添加了相同的类(每个单击事件),并使用返回不同值的数据标记。

基本上,我想在不同的时间跟踪所有的点击事件(7),并检查它们作为一张卡片。

如果用户在卡片内做了任何事情,将其算作一个事件。我基本上是在计算每张卡片的观看次数。

现在我有这样的东西

$(document).on("click", ".test", function() {
console.log('Testing Stats View capture');
var that = $(this);
var testStats = that.data('capture-stats');
console.log(testStats);   
}));

count view per card

您可以使用this.data():

在每张卡片上存储计数

$(document).on("click", ".card", function() {

var clickcount = $(this).data("clickcount") || 0;
clickcount++;
$(this).data("clickcount", clickcount);

console.log($(this).text() + " clicked: " + clickcount); 

});
.card { cursor: pointer; user-select: none;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='card'>card 1</div>
<div class='card'>card 2</div>
<div class='card'>card 3</div>

您可以在处理程序的末尾为触发事件的元素添加一个data属性,并在开始时检查它是否存在,作为执行给定逻辑的条件:

$(document).on("click", ".test", function() {
console.log('Testing Stats View capture');
var that = $(this);

//if the prop data-event-triggered is not set yet for this element
if ( !that.data('event-triggered') ){
var testStats = that.data('capture-stats');
//adds the prop data-event-triggered for this element
that.data('event-triggered','true');
console.log('event triggered-${testStats}');   
}    
});
.test {
width: 100px;
height: 100px;
background: gray;
cursor: pointer;
margin-bottom:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test" data-capture-stats="1">1</div>
<div class="test" data-capture-stats="2">2</div>

最新更新