如何创建一个函数来显示文本使用 jQuery 并且如果 img src 包含"is.png"则不执行?



我想创建一个函数,在所有地区的"请求定价"按钮上方显示文本,除非img src包含"is.png"。我的jQuery代码在插入时可以将文本添加到页面:

jQuery(".request-pricing").before("<div class='price-box' style='display:block!important;'><span class='regular-price' id='product-price'><span class='price' itemprop='price'>Starting from 1,123 EUR</span></span></div>");

具有"请求定价"类别的"请求价格"按钮的代码:

<a class="request-pricing fancybox.ajax" data-fancybox-type="ajax" href="/products/distributor/requestPricingForm?product_id=5265"> <button class="sc-button blue">Request Pricing</button> </a> 

当我不想运行函数时的代码(冰岛(:

<div class="country-flag">
<a href="/contact-us#country=IS">
<img src="https://cdn.stemcell.com/media/flag/is.png" alt="Iceland" title="Iceland">
</a>
<input type="hidden" class="hidden" id="geo_ip_country_code" name="geo_ip_country_code" value="IS">
</div>

我不知道如何运行我的jQuery代码,所以它总是执行,除非img src包含"is.png"。

这是我的尝试:

if ($(".country-flag img[src*='flag']")).ready(function showprice() {
$(".request-pricing").before("<div class='price-box' style='display:block!important;'><span class='regular-price' id='product-price'><span class='price' itemprop='price'>Starting from 1,123 EUR</span></span></div>");
}); else {
($(".country-flag img[src*='is.png']")).stop(function showprice() {
}

我只是在学习jQuery,所以我很感激任何反馈或资源。

我建议像这样使用.indexOf()

if ($(".country-flag img").attr("src").indexOf("flag")) {
var pb = $("<div>", {
class: "price-box"
}).css("display", "block !important").insertBefore($(".request-pricing"));
$("<span>", {
class: "regular-price",
id: "product-price"
}).appendTo(pb);
$("<span>", {
class: "price",
itemprop: "price"
}).html("Starting from 1,123 EUR").appendTo($("span", pb));
} else if($(".country-flag img").attr("src").indexOf("is.png")) {
// Do a thing
}

如果找到,.indexOf()将返回一个0或更高的整数。在if()语句中,-1和0的计算结果为False,1或更高的值为True。

查看更多:

  • https://api.jquery.com/insertbefore/
  • https://www.w3schools.com/jsref/jsref_indexof.asp
  • https://www.w3schools.com/jsref/jsref_if.asp

最新更新