PriceSelling没有定义。但它是

时间:2014-06-28 01:42:42

标签: javascript jquery

我收到错误PriceSelling未定义。但事实上,我知道它在页面上,因为它将它记录在控制台中。请帮忙!感谢

$.get(window.location, function(data){
   var regex=/<span class="it " data-se="item-privatesale-price">([\d,]+)<\/span>/;
   var PriceSelling = data.match(regex)[1];  
    console.log(PriceSelling);
});

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
} 

if (get('bot') && get('expecting') && get('expecting') == PriceSelling) {
console.log("It's a go!");
document.getElementsByClassName('conf-buy-now btn-primary btn-medium PurchaseButton ')[0].click();
//document.getElementById('conf-confirm-btn').click();
}; 

1 个答案:

答案 0 :(得分:0)

它在传递给$.get的回调函数的范围内定义。

但它没有在全球范围内定义。

你可以做到

var PriceSelling;

$.get(window.location, function(data){
  var regex=/<span class="it " data-se="item-privatesale-price">([\d,]+)<\/span>/;
  PriceSelling = data.match(regex)[1];  
  console.log(PriceSelling);
});

function get(name){
  if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
    return decodeURIComponent(name[1]);
} 

if (get('bot') && get('expecting') && get('expecting') == PriceSelling) {
  console.log("It's a go!");
  document.getElementsByClassName('conf-buy-now btn-primary btn-medium PurchaseButton ')[0].click();
  //document.getElementById('conf-confirm-btn').click();
} 

但是虽然你不会得到ReferenceError,但由于PriceSelling永远是undefined,所以它不会很好。

但我注意到你正试图立即使用响应。您必须在回调中使用它,一旦收到响应就会调用它。

您可能会受益于How do I return the response from an asynchronous call?

$.get(window.location, function(data){
  var regex=/<span class="it " data-se="item-privatesale-price">([\d,]+)<\/span>/;
  var PriceSelling = data.match(regex)[1];  
  console.log(PriceSelling);

  function get(name){
    if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
  } 

  if (get('bot') && get('expecting') && get('expecting') == PriceSelling) {
    console.log("It's a go!");
    document.getElementsByClassName('conf-buy-now btn-primary btn-medium PurchaseButton ')[0].click();
    //document.getElementById('conf-confirm-btn').click();
  } 
});