gpt4 book ai didi

javascript - jQuery 替换 html 文档中的开始和结束标记

转载 作者:行者123 更新时间:2023-11-28 00:11:54 25 4
gpt4 key购买 nike

我有以下 jQuery 片段,它应该将 [Button] Text Here [/Button] 之类的代码替换为类似的代码:

<a class="button">Text Here</a>

我的 javascript 如下:

$(document).ready(function() {

var buttonStart = $("body").html().replace(/\[Button\]*/ig,'<a class="button">');
$("body").html(buttonStart);

var buttonEnd = $("body").html().replace(/\[\/Button\]*/ig,'</a>');
$("body").html(buttonEnd);

});

我遇到的问题是它不断替换我页面上与标签 [Button] [/B​​utton] 无关的其他元素。例如以下内容:

  <div id="MiddleBarLeft"></div>

也被替换成

  <a class="button"><div id="MiddleBarLeft"></div></a>

我上面的正则表达式不应该只查找 [Button] 和 [/Button] 标签吗?

此外,还有其他有效的方法吗?

谢谢

=====================

更新..这是我的整个 HTML 文件,它替换了与我想要替换的内容无关的元素

    <html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {

var buttonStart = $("body").html().replace(/\[Button\]/ig,'<a class="button">');
$("body").html(buttonStart);

var buttonEnd = $("body").html().replace(/\[\/Button\]/ig,'</a>');
$("body").html(buttonEnd);

});
</script>


<style>
li{
list-style:none;
padding-top:10px;
padding-bottom:10px;}

.button, .button:visited {
background: #222 url(overlay.png) repeat-x;
display: inline-block;
padding: 5px 10px 6px;
color: #fff;
text-decoration: none;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
-moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
border-bottom: 1px solid rgba(0,0,0,0.25);
position: relative;
cursor: pointer
}
</style>



</head>
<body>

<div>
<ul>
<li>[Button]Test[/Button]</li>
<li></li>
<li>Sample Text</li>
</ul>
</div>


</body>
</html>

最佳答案

问题源于替换发生的方式 - 请考虑以下 fiddle : http://jsfiddle.net/GYrYa/

如您所见,最后有两个按钮,尽管只有一个 [Button][/Button] 语句 - 这是因为首先您要将 [Button] 替换为 <a class='button'>这会创建一个不匹配的标签。这会导致 </a>在最后添加。然后您将 [/Button] 替换为 </a> ,这会创建另一个不匹配的标签 - 这次是 <a> , 最后。

更好的解决方案是: http://jsfiddle.net/GYrYa/1/

编辑:http://jsfiddle.net/GYrYa/2/省略脚本标签匹配

编辑 2:http://jsfiddle.net/GYrYa/5/ - 最终解决方案,结合@Rain Diao 非贪婪匹配

编辑 3:添加了性能测试用例:http://jsperf.com/eithed-rsc3 ,请阅读下面@Rain Diao 的回答以了解其起源的讨论

关于javascript - jQuery 替换 html 文档中的开始和结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com