我有以下 HTML/JS,我在其中解析 DOM 元素并尝试找到丢失的元素并删除它们。然而,它说: includes()
不是一个函数。当我执行此操作时,我得到 newHTML
和 newHTMLO
的对象类型(newHTMLO 只是一个实验变量)。我尝试了 Array.from() 和 Object.valueOf() ,两者都产生相同的结果。
有人可以帮助我让它工作吗?
var deleteLinks = $(".remove-button .remove-from-cart");
console.log("registered: " + deleteLinks.length);
deleteLinks.on('click', function(ev){
ev.preventDefault();
console.log("registered: " + deleteLinks);
var currentHTML = $('.product');
var currentText = $('.product .product-details .name-header');
var newHTML ;
var deleteIndices = [];
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
newHTMLO = $(data).find('.product .product-details .name-header').map(function() { return this.innerText.toUpperCase(); });
newHTML = Object.values(newHTMLO);
for(i = 0; i < newHTML.length; i++){
console.log(i);
console.log(newHTML[i]);
console.log(typeof newHTML);
console.log(typeof newHTMLO);
if (!(newHTML.includes(currentText[i].innerText.toUpperCase()))) {
console.log("found mismatch for index " + i);
deleteIndices.push(i);
}
}
}
});
for(i = 0; i < deleteIndices.length; i++) {
console.log("removing " + deleteIndices[i]);
currentHTML[deleteIndices[i]].remove();
}
});
最佳答案
我认为您遇到的问题是您将 jQuery 对象数组视为常规对象数组,但事实并非如此。
更改这一行,看看是否可以解决您的问题...
newHTMLO = $(data)
.find('.product .product-details .name-header')
.toArray() // converts a jQuery object array to a regular array
.map(function() { return this.innerText.toUpperCase(); });
如果这没有帮助,那么我会将其删除为不相关。
这是一个例子。 Map1 是您当前的方法,map2 是修改后的版本...
var divs = $("body").find("div");
var map1 = divs.map(function(d) { return d.innerText; });
var map2 = divs.toArray().map(function(d) { return d.innerText; });
console.log("map1: " + map1)
console.log("map2: " + map2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>div #1</div>
<div>div #2</div>
<div>div #3</div>
<div>div #4</div>
关于Javascript include() 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623781/