2013-10-07 2 views
0

У меня возникла проблема с запуском этого скрипта. Он близок, но он продолжает бросать неопределенную ошибку в любое время, когда я добавляю что-либо к объекту кнопки.Другой неопределенный вопрос javascript

Вот HTML:

<div class="centerBoxContentsFeatured centeredContent back ie_margin" style="width:33%;"><div class="product-col"> 
       <div class="tie"> 
        <div class="indent2"> 
         <div> 
          <a class="name" href="http://localhost:8080/rfs700/index.php?main_page=product_info&amp;cPath=37&amp;products_id=128">TB-0070 Tabletop Interpreter Booth</a> 
         </div> 
         <div class="img"> 
          <a href="http://localhost:8080/rfs700/index.php?main_page=product_info&amp;cPath=37&amp;products_id=128"><img src="images/products/tb0070.jpg" alt="TB-0070 Tabletop Interpreter Booth" title=" TB-0070 Tabletop Interpreter Booth " width="130" height="130"></a> 
         </div> 
         <div class="desc"> 
          The TB-0070 Tabletop Interpreter Booth accommodate... 
         </div> 
         <div class="price"><strong><img src="includes/templates/template_default/images/call_for_prices.jpg" alt="Call for Price" title=" Call for Price " width="78" height="20"></strong></div> 
         <div class="buttons"> 
          <a href="http://localhost:8080/rfs700/index.php?main_page=products_new&amp;action=buy_now&amp;products_id=128"><img src="includes/templates/theme324/buttons/english/button_in_cart.gif" alt="Add to Cart" title=" Add to Cart " width="106" height="27"></a><a href="http://localhost:8080/rfs700/index.php?main_page=product_info&amp;cPath=37&amp;products_id=128"><img src="includes/templates/theme324/buttons/english/button_goto_prod_details.gif" alt="Go To This Product's Detailed Information" title=" Go To This Product's Detailed Information " width="58" height="27"></a> 
         </div> 
        </div> 
       </div> 
      </div></div> 

Вот мой Javascript код:

<script type="text/javascript"> 
    $(document).ready(function() { 
     var doc = $(".centerBoxContentsFeatured .price"); 
     doc.each(function(){ 
      var image = $(this).find("img").attr("alt"); 
      var button = $(this).find(".buttons"); 
      if (image == "Call for Price"){ 
       alert(button.find("a:first-child").attr("href")); 
      } 
     }); 
    }); 
</script> 

Когда я только оповещения (кнопка) отображает его как объект. Но если я добавлю что-нибудь еще к объекту кнопки, например, то, что показано в приведенном выше javascript-коде, отображается неопределенно. Есть идеи?

+0

[объект Object] не означает, что элемент был найден. В этом случае 'button.length' является' 0', и это полностью объясняет, почему 'button.find (« ничего »). Attr (« something »)' undefined. –

ответ

1

$(".centerBoxContentsFeatured .price") не содержит .buttons. Вам нужно пройти на один уровень, чтобы вернуть документ.

<script type="text/javascript"> 
    $(document).ready(function() { 
     var doc = $(".centerBoxContentsFeatured .price"); 
     doc.each(function(){ 
      var image = $(this).find("img").attr("alt"); 
      var button = $(this).parent().find(".buttons"); 
      if (image == "Call for Price"){ 
       alert(button.find("a:first-child").attr("href")); 
      } 
     }); 
    }); 
</script> 
+0

Ahhhh. Спасибо вам, сэр, я вижу вашу точку зрения, и проблема решена. Спасибо за помощь! – i3i2uno

+0

Рад, что было быстро;) – Brian

0

var doc = $(".centerBoxContentsFeatured .price"); возвращается ниже элемент HTML

<div class="price"> 
    <strong> 
    <img src="includes/templates/template_default/images/call_for_prices.jpg" alt="Call for Price" title=" Call for Price " width="78" height="20"> 
    </strong> 
</div> 

здесь нет кнопки так $(this).find(".buttons") выходов пустого объекта
когда вы делаете дополнительную button.find("a:first-child") операции по кнопке, это вернет null и, следовательно, вы будете get исключение при попытке получить доступ к attr.

1

Там проблема в то время как вы называете button событие, потому что он находится вне вас $(".centerBoxContentsFeatured .price")

А также в то время как вы называете что-то вроде этого убедитесь, что событие вы вызываете внутри этого элемента как сейчас его находится вне вашего div и поэтому отображается ошибка.

Теперь,, чтобы удалить это, вам нужно напрямую позвонить по кнопке или ссылке с помощью точного элемента, в котором он находится.

Вы решение для этого:

<script type="text/javascript"> 
    $(document).ready(function() { 
     var doc = $(".centerBoxContentsFeatured .price"); 
     doc.each(function(){ 
      var image = $(this).find("img").attr("alt"); 
      var button = $(this).parent(".tie").find(".buttons"); 
      if (image == "Call for Price"){ 
       alert(button.find("a:first-child").attr("href")); 
      } 
     }); 
    }); 
</script> 
0

.buttons класса не является детьми .centerBoxContentsFeatured .price является родственным. Используйте siblings метод:

Описание: Получить братьев каждого элемента в наборе соответствующих элементов , необязательно отфильтрованных с помощью селектора.

Код:

$(document).ready(function() { 
    var doc = $(".centerBoxContentsFeatured .price"); 
    doc.each(function() { 
     var image = $(this).find("img").attr("alt"); 
     var button = $(this).siblings(".buttons"); 
     if (image == "Call for Price") { 
      alert(button.find("a:first-child").attr("href")); 
     } 
    }); 
}); 

Демонстрация: http://jsfiddle.net/IrvinDominin/d5UTW/

Смежные вопросы