在jquery中拆分文本

时间:2016-05-26 11:14:30

标签: jquery

我有以下jQuery代码。

innerHtml = innerHtml + '<div class="compare-box '+ $(this).attr("offertype") +'"> <div class="compare-close"><span class="closed" onclick="RemoveCompareOffer(\''+ $(this).attr("id") + '\')"><i class="fa fa-times"></i></span></div>'
             + '<div class="compare-logo"><img src="' + $(this).attr("imagelink") + '" /></div><p>' + $(this).attr("offername") + '</p>'
             + '<input type="button" value="View Details" class="viewbtn" onclick="CallOfferRenderAction(\'' + $(this).attr("offercode") + '\',\'' + $(this).attr("providercode") + '\')" /></div>';

每当$(this).attr("offertype")包含special-box specialoffer时,我想拆分并将其替换为specialoffer-compare。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

使用临时变量和indexOf()检查字符串是否包含子字符串,如下所示: -

var temp = $(this).attr("offertype");
temp = temp.indexOf("special-box specialoffer") > -1 ? "specialoffer-compare" : temp;

innerHtml = innerHtml + '<div class="compare-box '+ temp +'"> <div class="compare-close"><span class="closed" onclick="RemoveCompareOffer(\''+ $(this).attr("id") + '\')"><i class="fa fa-times"></i></span></div>'
             + '<div class="compare-logo"><img src="' + $(this).attr("imagelink") + '" /></div><p>' + $(this).attr("offername") + '</p>'
             + '<input type="button" value="View Details" class="viewbtn" onclick="CallOfferRenderAction(\'' + $(this).attr("offercode") + '\',\'' + $(this).attr("providercode") + '\')" /></div>';