我的代码是否正确?替换href链接文本
function replace_stuff() {
document.body.innerHTML = document.body.innerHTML.replace(/oldtexts/g,'');
}
我想一个a href
标签之间移除字符串“oldtexts”像这样 但<a href ="#">oldtexts</a>
我仍然看到oldtexts并没有什么被替换
我的代码是否正确?替换href链接文本
function replace_stuff() {
document.body.innerHTML = document.body.innerHTML.replace(/oldtexts/g,'');
}
我想一个a href
标签之间移除字符串“oldtexts”像这样 但<a href ="#">oldtexts</a>
我仍然看到oldtexts并没有什么被替换
我没有尝试这一个,但是这可能工作。 (用了jQuery)
$('a[href]').each(function(i){
if($(this).html()=="oldtext") $(this).html(" ");
});
或
$('a[href]').each(function(i){
$(this).html($(this).html().replace(/regex/g,"blahblah"));//warning : if replaced text contains nothing(""), then this will not work.
});
您已经标记了jQuery的,所以我建议使用它:
$(function(){
$('a').each(function(){
var $this = $(this);
$this.html($this.html().replace(/oldtext/g, ''));
});
});
使用jQuery :)
$(document).ready(function(){
$('#idofatag').text('replacevalueofoldtexts');
});
如果你想通过点击一个屁股触发这个改变上
$(document).ready(function(){
$('#someButtonid').click(function(){
$('#idofatag').text('replacevalueofoldtexts');
});
});
如果您尝试使用/\b(oldtexts)\b/g
或jQuery的.replace
会发生什么?
由于您似乎在使用jQuery,因此最干净的解决方案似乎使用了function for .html()
。
$('a').html(function (index, oldhtml) {
return oldhtml.replace(/oldtexts/g, '');
});
如果你想编写一个可重复使用的功能,你可以做到这一点,当然:
function replace_stuff(index, oldhtml) {
return oldhtml.replace(/oldtexts/g, '');
}
然后你就可以调用任何jQuery对象上:$('a').html(replace_stuff);
。
'oldtext'永远不会匹配'/ oldtexts/g',还是只是一个错字? :) – DarthJDG 2011-05-12 07:36:17
@DarthJDG错字谢谢 – sarsar 2011-05-12 07:37:09