[英]Splice removing random elements issue in javascript
I am trying create interactive shopping cart using jQuery, but splice issue ruined everything, because when I am delete element directly it works perfect to me, but than I am going to dynamically changes it doesn't work deleting random elements in array even after updates indexes. 我正在尝试使用jQuery创建交互式购物车,但是拼接问题破坏了一切,因为当我直接删除元素时,它对我来说是完美的,但是比起我要动态更改,即使在更新后删除数组中的随机元素也无法工作索引。
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<div id="myDIV2"></div>
<div id="myDIV"></div>
<script>
var wishlistArray = ["Item1", "Item2", "Item3", "Item4", "Item5"];
function wishlist_show() {
var wishlistArrayDom = "";
jQuery.each(wishlistArray, function (i, wishlistID) {
wishlistArrayDom += '<div><a href="javascript:;" class="rem-from-wishlist" value="' + i + '">Remove( ' + wishlistID + ' )</a></div>';
});
$('#myDIV').empty();
$('#myDIV').html(wishlistArrayDom);
wishlist_update_rem();
console.log('All: ' + wishlistArray.length);
console.log('Arr: ' + wishlistArray);
}
function wishlist_rem(num) {
console.log('Value: ' + $(this).attr('value'));
console.log('All: ' + wishlistArray.length);
console.log('Arr: ' + wishlistArray);
$(this).parent().slideUp("slow", function () {
console.log(wishlistArray.splice($(this).attr('value'), 1));
wishlist_show();
});
$('#myDIV2').append('<br>Remove ' + wishlistArray[parseInt($(this).attr('value'))] + ' of element' + +$(this).attr('value'));
}
wishlist_show();
function wishlist_update_rem() {
$(".rem-from-wishlist").unbind("click");
$(".rem-from-wishlist").click(wishlist_rem);
}
</script>
UPDATE: Solved by myself, thanks to all, stackoverflow is best. 更新:我自己解决了,感谢所有人,stackoverflow是最好的。
Ready to used jsfiddle http://jsfiddle.net/ar0zrxwc/ 准备使用jsfiddle http://jsfiddle.net/ar0zrxwc/
It's not an issue with splice()
, it's an issue with your scoping of this
. 与
splice()
无关,这与您this
的范围有关。
Change your removal function to this: 将您的删除功能更改为此:
function wishlist_rem(num) {
var idx = parseInt($(this).attr('value')));
$(this).parent().slideUp("slow", function () {
wishlistArray.splice(idx, 1));
wishlist_show();
});
$('#myDIV2').append('<br>Remove ' + wishlistArray[parseInt($(this).attr('value'))] + ' of element' + +$(this).attr('value'));
}
Your problem is that this
inside the animation callback is the parent of the element clicked which has no value attribute. 你的问题是,
this
动画回调里面是元素的父点击它没有价值属性。 Just define a variable at the same point that you are currently logging the index value. 只需在当前记录索引值的同一点定义一个变量。
function wishlist_rem(num) {
var index = parseInt( $(this).attr('value'),10);
$(this).parent().slideUp("slow", function () {
console.log(wishlistArray.splice(index, 1));
wishlist_show();
});
$('#myDIV2').append('<br>Remove ' + wishlistArray[parseInt($(this).attr('value'))] + ' of element' + +$(this).attr('value'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.