所以我有以下jQuery代码:
function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
var regex = new RegExp(getUrlParameter('suche'),"gi");
$('table td').each(function () {
$(this).html($(this).text().replace(regex,'<span class="yellow">$&</span>'));
});
它执行它必须做的事情(在包含给定搜索字符串的表中标记字符串),但它也删除该表中的所有<a href>
。表格如下:
<table>
<tr>
<th>Head</th>
</tr>
<tr>
<td>some content including search strings</td>
<td>
<a href="profile.php?search=$search string&id=$id">Profile</a>
</td>
</tr>
起初我认为这是因为它包含被<span>
取代的搜索字符串,但即使没有它也不会起作用。如果我右键单击&gt;查看源代码,它甚至没有显示链接(它看起来像<td>Profile</td>
)。我完全不知道它来自哪里,但它肯定与jQuery有关,因为如果我评论它,链接就像预期的那样。
答案 0 :(得分:1)
您正在拨打text()
,其中仅包含&#34;个人资料&#34;在你的第二个td
。
<td><a href="....">Profile</a></td>
您正在对该字符串进行替换,然后调用html()
将其用作td
的整个内容:
<td>Profile</td>
如果您非常确信您的替换文字与您的HTML不冲突,那么您想说:
$(this).html(
$(this).html().replace(regex,'<span class="yellow">$&</span>')
);
保存您的代码。但你最安全的选择是只在文本节点中替换。例如,请参阅Replace text inside a div without affecting any HTML tags inside of it