脚本不使用Internet Explorer - 简单的dom scrape with querySelectorAll并推入数组

时间:2015-04-16 19:44:48

标签: javascript internet-explorer

我对Javascript不是很有经验,所以当我设法创建这个脚本时,我感觉非常好。但是,唉,它似乎失败了Internet Explorer,我不知道为什么。

有人能发现IE不喜欢这个剧本吗?

从我们的Google Analytics内部看,此脚本在IE 9和11中失败。

function() {

// build products object
var prods = [];
var count = document.querySelectorAll('.txtStayRoomLocation').length;

for(i=0; i < count; i++) {

    //set granular vars
    prd = {};
    var brand = document.querySelectorAll('.txtStayRoomLocation')[i].textContent;
    var name = document.querySelectorAll('.txtStayRoomDescription')[i].textContent;
    var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount')[i].textContent;
    var quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;

    //add to prd object
    prd.brand = brand;
    prd.name = name;
    prd.price = price;
    prd.quantity = quantity;

   //add to prods array
   prods.push(prd);
}

   var ecommerceData = {
    'ecommerce': {
      'purchase': {
       'actionField': {'id': {{transaction id}},
                       'revenue': {{transaction amount}},
                       'tax': {{tax}}},

       'products': prods
      }
    }
   };
   return ecommerceData;
}

1 个答案:

答案 0 :(得分:1)

关于@romuleald所说的内容,这可能是构建代码的更好方法。每次通过 for 循环时,它都不需要找到相同的数组。

function() {
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');

for(i=0; i < brand.length; i++) {

//set granular vars
var prd = {};

//add to prd object
prd.brand = brand[i].textContent;
prd.name = name[i].textContent;
prd.price = price[i].textContent;
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;

//add to prods array
prods.push(prd);
}

var ecommerceData = {
'ecommerce': {
  'purchase': {
   'actionField': {'id': {{transaction id}},
                   'revenue': {{transaction amount}},
                   'tax': {{tax}}},

   'products': prods
  }
}
};
return ecommerceData;
}

至于错误,你能告诉我们更多细节吗?调试器中抛出了什么错误?