在我的插件中覆盖html();
内容时遇到问题。问题是它不会根据条件返回null(空白)
插件的逻辑是它通过减去跨度值的百分比来替换<span>
中的所有元素。该插件根据以下条件更改<span>
内的文字:
基本上我想根据设定的条件显示促销标签,但无论条件如何,销售标签始终显示。
这是插件:
(function($) {
$.fn.TTprices = function(options){
// Default Settings
//
var settings = $.extend({
threshold : 899,
discount : 40,
exclude : ['xxx', 'xdd']
}, options);
return this.each(function() {
var $this = $(this);
var $value = $this.contents()[0].textContent;
var $price = parseFloat($value);
var $discount = "." + (settings.discount);
var $total = $price - ($price * $discount);
var $productID = $this.data('product-id');
var $exclude = (settings.exclude);
var $saleTag = $("span[data-badge='priceline']"); // Sale Tag
$this.html(function(){
if ($.inArray($productID, $exclude) !== -1) {
$saleTag.html(); // Sale tag off
return $this.html();
}
else if ($value != (settings.threshold)) {
$saleTag.html(settings.discount + '% OFF'); // Sale tag on
return $this.html().replace($value, $total.toFixed(2)+" ");
}
else {
$saleTag.html(); // Sale tag off
return $this.html();
}
});
});
};
}(jQuery));
HTML:
<span class="price" data-product-id="xkk">1999 <span class="currency">KR</span>
<span class="sale" data-badge="priceline"></span>
</span><br>
<span class="price" data-product-id="xxx">3999 <span class="currency">KR</span>
<span class="sale" data-badge="priceline"></span>
</span><br>
<span class="price" data-product-id="ccc">2499 <span class="currency">KR</span>
<span class="sale" data-badge="priceline"></span>
</span><br>
答案 0 :(得分:2)
您没有正确选择$saleTag
元素。您使用的代码是:
var $saleTag = $("span[data-badge='priceline']"); // Sale Tag
选择所有span
标签,其data-bagde属性等于priceline。
正确的代码应该是:
var $saleTag = $this.find("span[data-badge='priceline']"); // Sale Tag
选择span
循环中当前.price
元素内的each()
标记。