简体   繁体   English

将括号内的文本替换为标签的Javascript不适用于<style>

[英]Javascript that replaces bracketed text into tags, doesn't work with <style>

I have a piece of jquery, that replaces brackets {} with <> that are inside the body: 我有一段jquery,用体内的<>替换了括号{}

JQuery: jQuery的:

window.onload=function() {
$("body").children().html(function (_, html) {
    return html
    .replace(/\{/g,"<")     
     .replace(/b\@/g,"strong")
.replace(/\!/g,"/")
    .replace(/\}/g,">");
});
}

HTML 的HTML

<!DOCTYPE HTML>
<html>

<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="tags.js" type="text/javascript"></script>
<meta charset="utf-8">
<title>Something</title>
</head>
<body>
<w>
<style>
.red {
color: red;
}
</style>
{style}
body {
background-color:red;
}
{!style}

{b@ class="red"}
Some Bold Text
{!b@}

</w>
</body>
</html>

But when I try putting in a {style} tag substitiute, the style tags work, but no CSS is actually rendered. 但是,当我尝试放置{style}标签替代品时,style标签起作用了,但是实际上没有呈现CSS。 Also I when I try applying the color:red in an normal style tag to the .red {b@} it doesn't work, but it works if I apply the style inline. 同样,当我尝试将普通样式标签中的color:red应用到.red {b@}它不起作用,但是如果我以内联方式应用样式,则它可以工作。

The question is: Is there any way to make the CSS render properly inside the style tags? 问题是:有什么方法可以使CSS在样式标签中正确呈现?

You're very close. 你很亲密 You just need to add these lines at the end of your code: 您只需要在代码末尾添加以下行:

$('style').appendTo('head').text(function() {
  return $(this).text().replace(/\</g,'{').replace(/\>/g,'}');
});

This moves the style elements to the head , and it undoes the text substitutions in your previous code for those elements. 这会将style元素移到head ,并且取消了先前代码中这些元素的文本替换。

Snippet: 片段:

 window.onload=function() { $("body").children().html(function (_, html) { return html .replace(/\\{/g,"<") .replace(/b\\@/g,"strong") .replace(/\\!/g,"/") .replace(/\\}/g,">"); }); $('style').appendTo('head').text(function() { return $(this).text().replace(/\\</g,'{').replace(/\\>/g,'}'); }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <w> <style> .red { color: red; } </style> {style} body { background-color:yellow; } {!style} {b@ class="red"} Some Bold Text {!b@} </w> </body> 

正如@barmar所说, {}覆盖了CSS括号,因此我只是将{}更改为[] ,因此不会造成干扰。

It's because the <style> tag hasn't been compiled by the browser since you wrote {style} ,you can't make it work by replacing {} by <> . 这是因为自编写{style}以来,浏览器尚未编译<style>标记,因此无法通过将{}替换为<>来使其起作用。 You need to replace as your script is doing, then load all the code in jquery and append it to the page 您需要在脚本执行过程中进行替换,然后将所有代码加载到jquery中并将其附加到页面上

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

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