简体   繁体   English

将HTML代码存储到javascript变量

[英]Store html code to javascript variable

I have a problem when converting store html code to javascript variable, I know we can convert using converter tools, but I can't use this converter in my situation. 将商店html代码转换为javascript变量时遇到问题,我知道我们可以使用转换器工具进行转换,但在我的情况下无法使用此转换器。

I am trying the following code 我正在尝试以下代码

 var t_cls="font-effect-anaglyph rotator"; var randompostsurl="www.allinworld99.blogspot.com"; var randompoststitle="Open Inspect Element And see the Code"; var default_script = "<script> document.write('<div><a class="+t_cls+" href=\\"' + randompostsurl + '\\" rel=\\"nofollow\\">' + randompoststitle + '<\\/a><\\/div>'); <\\/script>\\n"; $("#apnd").append(default_script); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <div id="apnd"></div> 

The above one will produce the following output 上面的将产生以下输出

<a class="font-effect-anaglyph" rotator="" href="www.allinworld99.blogspot.com" rel="nofollow">Open Inspect Element And see the Code</a>

Why the rotator class will created as new attribute? 为什么将rotator类创建为新属性?

Because there are no quotes around the class attribute in the result. 因为结果中的class属性没有引号。 You need to add them, since you have a space in the attribute's value: 由于属性值中有空格,因此需要添加它们:

default_script = "<script>        document.write('<div><a class=\""+t_cls+"\" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";
// Here --------------------------------------------------------^^---------^^

替换您的default_script代码

 default_script = "<script>        document.write('<div><a class='"+t_cls+"' href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";

As there are no quotes in class, it produce rotator as a new attribute. 由于类中没有引号,因此它将rotator作为新属性产生。 But you can achieve rotator as a class by the following way. 但是您可以通过以下方式将rotator作为一个类来实现。 ie replacing single quotes with escape sequence. 即用转义序列替换单引号。

<script>$(document).ready(function(){
 var t_cls="font-effect-anaglyph rotator", randompostsurl="www.allinworld99.blogspot.com",
 randompoststitle="Open Inspect Element And see the Code",
 default_script = "document.write(\"<div><a class=\""+t_cls+"\" href=\"" + randompostsurl + "\" rel=\"nofollow\">\" + randompoststitle + \"<\/a><\/div>\");<\/script>\n";
$("#apnd").append(default_script);
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM