2009-02-22 270 views
0

我一直在致力于一个项目,动态地创建一个JavaScript文件使用ASP.NET从另一个网站调用。jquery追加使用多行

这个jQuery JavaScript文件追加一个div,并用相当大的HTML代码段来填充它,为了做到这一点,我需要把段放到一个字符串,像这样:

$(document).ready(function(){ 
var html = "Giving this magazine such a lofty epithet may seem a bit presumptuous, but for a non scientifically trained outsider this magazine offers a fresh and challenging look at the fast paced world of science that doesn't shy away from humor and the use of terms and ideas that may require its readers to go online and define a term. And in some cases it may inspire the reader to pick up a book on science by such greats as Hawking and Greene in order to better grasp some of the concepts dealing with time, space and atoms. This magazine isn't dumbed down. It includes well placed and efficient illustrations to help explain some of the more abstract points. It is not designed in the way popular magazinea are, in so much as they only touch upon a topic in the simplest manner and then move on before the audience is lost. Yet this magazine keeps the attention of the reader by combining explanatory notes that help people with no background knowledge have some grasp of the topic and by using humor and well written articles to clearly make their points. <br />For a magazine with a serious and well researched list of topics having small cartoons the likes of the New Yorker shows how comfortable this magazine is with itself. From the moment I picked up this magazine for the first time I felt like every word I read mattered and was worth my time to read. (Not true of many other magazines) American Scientist may not have the audience of Discover or National Geographic, nor is it as accessible as said titles, but for those with a true interest in science willing to challenge themselves and commit to real learning this magazine may be a perfect fit. At $4.95 it is certainly worth it to pick a copy on the news stand and try it out." 

$("#divname").append(html); 
}); 

正如你所看到的段会非常大,我无法知道它有多大,因为它是从我的数据库动态生成的,具体取决于用户在请求中定义的reviewID。

要插入div的html是评论的列表,并且由通过列表循环的转发器使用asp.net MVC生成。 (如果这有助于让你知道我在做什么)。

有没有什么办法可以将这个大的段变成一个可以插入到追加脚本中的字符串?

谢谢

+0

我认为var html =“long string here ...”方法应该可行,不是吗? – 2009-02-22 07:49:59

+0

如果字符串是以html形式生成的,并且不只是形成一个长字符串,则会因某种原因创建新行。 – 2009-02-22 08:50:10

回答

0

纠正我,如果我错了,但我认为在开始和结束引号之间的一切都将被视为该字符串的一部分,不管有多少行了。除非你的字符串本身有任何引号,在这种情况下,最好在你的字符串中使用ASP的php's addslashes()函数,它应该在字符串中的所有"标记之前添加一个\

另一个想法是使用Json对字符串进行编码/解码。

1

一些想法:

  • 可以更换新线与空间,创造了巨大的线。它不应该有问题。
  • 使用字符串连接。拆分字符串和线,并做:

    var html = line1 + line2 + ... 亚麻;

  • 做一个Ajax调用来填充DIV:

    $( “#divname”)负载(SERVICE_URL);

您需要创建一个将返回字符串的服务。

在我看来,第三个选项比其他的更好。

+0

我同意,第三个选项将是一个非常好的选择,但它似乎并没有跨域工作。你能让它为你跨域工作吗? – 2009-02-22 08:14:47

+0

您可以在$ .ajax调用中使用jsonp作为dataType从外部域加载数据。这不会像负载那么简单。然而,为什么你想这样做呢?为什么不在与网页相同的域中创建代理? – kgiannakakis 2009-02-22 09:02:06

0

我没有看到有什么问题,只生成一个大屁股长的单行字符串,并像你一样附加它。期。完成。 Fancier不会为你带来任何收益。

0

隐藏它其他地方在页面上,并用它填充DIV当你需要它?