2
我一直在研究一個簡單的代碼,它可以檢測一個項目已經收到多少點擊,並且會將它放在列表的頂部,問題是,我可以只需更換第一個項目,如果再次單擊它,則不會增加項目內部的點擊次數。爲什麼是這樣?無法在jQuery上對我的html列表進行排序
我的代碼:(按Ctrl + Shift + I),並檢查items
看到他們改變
$(function() {
$('.watchMe > .item').attr({
"influence": "0"
});
});
$('.watchMe > .item').mousedown(function() {
$(this).attr({
"influence": parseInt($(this).attr("influence"), 10) + 1
});
});
$(document).on('mouseup', function(e) {
rearrangeEm();
});
function rearrangeEm() {
var tempArray = [];
$('.watchMe > .item').each(function() {
tempArray.push([this, parseInt($(this).attr("influence"), 10)]);
console.log(this);
});
for (var i = 0; i < tempArray.length; i++) {
for (var j = i + 1; j < tempArray.length; j++) {
var temp;
if (tempArray[i][1] < tempArray[j][1]) {
temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
$('.watchMe').empty();
for (i = 0; i < tempArray.length; i++) {
$('.watchMe').append(tempArray[i][0]);
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>smartSystem</title>
<style>
.item {
height: 100px;
border: 1px solid #c3c3c3;
}
</style>
</head>
<body>
<div class="watchMe">
<div class="item">a</div>
<div class="item">b</div>
<div class="item">c</div>
</div>
</body>
</html>
哦,這是棘手的,我不知道該事件實際上是有界的元素,非常感謝你羅裏,你救了我的生命..對不起 – Kyle
我可能愚蠢的問題,這表明我缺乏對jQuery的知識,但$(this).data('influence')|| 0意思是?這個還是0?如果這是undefined/null,那麼分配0? – Kyle
就是這樣。您可以使用布爾類型強制來爲變量添加一個默認值。 –