2011-11-07 52 views
1

我想使用.replaceWith来替换单词到一个函数,但它不工作我认为问题是,我没有正确的功能正确,但我不知道如何编写它对。任何人都可以帮助我(这只是微乎其微)。谢谢。.replaceWith替换为功能

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"> 
<html> 
<body> 

<script type="text/javascript"> 

var d=new Date(); 
var weekday=new Array(7); 
weekday[0]="Monday"; 
weekday[1]="Tuesday"; 
weekday[2]="Wednesday"; 
weekday[3]="Thursday"; 
weekday[4]="Friday"; 
weekday[5]="Monday"; 
weekday[6]="Monday"; 


</script> 


<script type="text/javascript"> 

$(document).ready(function($){ 
    $('div.Shipby').replaceWith(function(){ 
     return $("<div>").text("Orders placed now will ship " + weekday[d.getDay()]); 
    }); 
}); 

</script> 

    <div class="Shipby"> 
     Tomorrow. 
    </div> 
</body> 
</html> 
+1

这不是'replaceWith'的工作方式。请[阅读文档](http://api.jquery.com/replaceWith/)。并且使用'document.write'是非常错误的。 –

+0

不是'document.write()'覆盖*整个*文件吗? –

+0

@DavidThomas:我认为是。 – Blender

回答

2

由于搅拌机说,这听起来像它会更容易只需要升级texthtml,但如果你想使用replaceWith,你可以做这样的:

$(document).ready(function($){ 
    $("div.Shipby").replaceWith(function(){ 
     return $("<div>").text("Orders placed now will ship " + weekday[d.getDay()]); 
    }); 
}); 

这里有一个的jsfiddle:http://jsfiddle.net/TbE6P/

+0

你忘了返回。 – SLaks

+0

我认为OP会因此而感到困惑;)但是,这是'.replaceWith()'完全有效的用法。 – Blender

+0

@SLaks:谢谢,刚才注意到了。固定。 –

6

只需设置text()

$('div.Shipby').text("Orders placed now will ship " + weekday[d.getDay()]); 

或者,如果你计划,包括您的字符串HTML的html()

$('div.Shipby').html("Orders placed now will ship " + weekday[d.getDay()]); 

没有必要使用document.write()

+0

+1:绝对是最简单的解决方案。 –