动态链接创建不同

时间:2012-12-07 12:19:26

标签: javascript jquery regex internet-explorer split

我的字符串:

"<SPAN style=\"COLOR: #000000; PADDING-RIGHT: 30px\">Reason 1:</SPAN> My Text Here!"

Internet Explorer:

"SPANstyleCOLOR000000PADDINGRIGHT30pxReason1SPANMyTextHere"

其他浏览器:

"Reason1BankbeatingexchangeratesCompareourratestoday"

// Remove all characters, keep alphanumerical + spaces 
reasonTitleSpaces = reasonTitle.replace(/[^A-Za-z0-9\s]+/g, '');

// Remove all characters, keep alphanumerical
reasonTitle = reasonTitle.replace(/[^A-Za-z0-9]+/g, '');

2 个答案:

答案 0 :(得分:1)

您可以使用jQuery API创建链接,而不是将其作为字符串...

进行操作

这将为您提供更好的结果和跨浏览器兼容性。

而不是reasonTitle = $(this).html();,克隆DOM结构,以便您可以在不更改页面的情况下自由操作:

<script>
reasonTitle = $(this).clone();

//Remove the span tag, now you have only the reason
reasonTitle.find('span').remove()

//Get the text value
reasonTitle = $.trim(reasonTitle.text());

//Create the anchor
anchorLink = $("<a />",{id:'anchor', name:reasonTitle})
$(this).parent().before(anchorLink);

//You don't need to count your `<li>`, use `<ol>` for ordinal lists
//Create the link:
$("<a />",{href:'#'+reasonTitle}).click(function(){
    _gaq.push(['_trackEvent', experimentConversionReference, 'ReasonClicked', $(this).text()]);
}).text(reasonTitle );
</script>

答案 1 :(得分:0)

我知道它很脏但它能完成这项工作

// Remove extras for IE
reasonTitle = reasonTitle.split("Reason").slice(1).join("Reason");
reasonTitleSpaces = reasonTitleSpaces.split("Reason").slice(1).join("Reason");

// Remove any extra occurances of "span" for IE
reasonTitle = reasonTitle.replace("SPAN","");
reasonTitleSpaces = reasonTitleSpaces.replace("SPAN","");