jQuery ID选择器hack / workaround?

时间:2016-02-23 11:19:48

标签: jquery

我有一个朋友,他的网站使用Joomla和各种模块/插件。他想要的是,任何与某个金额相匹配的价格都会被POA取代,但是,他使用的Joomla插件会以价格为代价,因此jQuery只能找到第一个实例而不会将其余部分更改为POA。作为一种解决方法,我使用了一个类选择器,它基本上是每个产品的容器:

    $('.vehiclelist_right:contains("1,000,000")').html($('.vehiclelist_right:contains("1,000,000")').html().replace('1,000,000', 'POA'));
$("span#auto_maintitle_price").css("visibility", "visible");

这很有效,在我们隐藏价格的CSS中,然后在页面加载后使用jQuery取消隐藏它们以避免向客户显示1,000,000英镑。现在,自从更改为类选择器后,单个页面(一旦您点击产品)的价格就不会像使用旧代码时那样取消隐藏价格:

$('#auto_maintitle_price').html($('#auto_maintitle_price').html().replace('1,000,000', 'POA'));
         $("span#auto_maintitle_price").css("visibility", "visible");

它保持可见性:隐藏; 有没有人有任何好主意/黑客/办公室?

1 个答案:

答案 0 :(得分:0)

您在第二个示例$("span#auto_maintitle_price")中使用的ID选择器 如果您有多个带有<span> ID的auto_maintitle_price代码,则只会选择列表中的第一项。

你仍然应该使用相似元素的类,或使用$.each迭代所有这些元素:

$("span#auto_maintitle_price").each(function(){
  // $(this) - is now each of the items
  var initialValue = $(this).html();
  $(this).html(initialValue.replace('1,000,000', 'POA')).css("visibility", "visible");
})