触发动态元素的jquery

时间:2011-12-06 15:43:35

标签: jquery

我正在尝试在div上触发.show,当链接有一个动态添加的类时,它的父级具有在选择(点击)时添加的类pdSelectedSwatch

示例代码:

<li class="pdSelectedSwatch">
   <a href="javascript:void(0)" class="outOfStock">
      <img class="outOfStock" src="/outofstock.gif" > 
   </a>
</li>



if ($("a.outOfStock").parent().hasClass("pdSelectedSwatch")) {
    $(".stockMessage").show();
}

但我无法让它正常工作,我打赌我的语法已关闭。

我应该注意outOfStock类是由xml文件中的值决定的,并且有几个函数根据该文件确定链接的类。

我还应该注意该网站使用的是jQuery 1.4.2,该版本不会在第3时间更新。

感谢。

1 个答案:

答案 0 :(得分:1)

我们可以使用你的一些html来确保选择器是正确的吗?

响应用户编辑

//if the xml is parsed and used on page load, then just find the offending a.outOfStock elements
$(document).ready(){
//.find assumes the stock message is a child of the a.outOfStock Element.
// i am inferring there could be multiple a.outOfStocks on a page, and the message is localized.
 $(".pdSelectedSwatch > a.outOfStock").find(".stockMessage").fadeIn("slow");
}

//a global ajax complete event, you must check the uri used to be sure it is the ajax call you care about!
// you should probably add a 'complete' event to the original ajax call if you have control of it
// if you're still reading, then you may not be in control of the xml ajax call.
// you can still listen for a jQuery complete event.  this only works if the xml ajax call used jQuery as well.
$('selector for whatever called the ajax').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/uri/you/used/to/get/the.xml') {
    $(".pdSelectedSwatch > a.outOfStock").find(".stockMessage").fadeIn("slow");
  }
});

// as of 1.4.2
$(".pdSelectedSwatch > a").delegate(".outOfStock","click", function(event){
         $(".stockMessage").show();
        });