【发布时间】:2016-02-12 12:51:27
【问题描述】:
我有这段代码可以从 HTML 电子邮件中的链接标签中删除所有空格。代码运行良好,我得到的唯一问题是它似乎删除了 head 标记内的内容,并删除了输出时的打开 <body> 和关闭 </body> 标记。有人可以帮我理解发生了什么吗?
JSBin here.
我的 JavaScript 代码如下:
$('#submit').click(function(){
var original = $('#replace').val();
var output = $('<html/>').html(original);
output.find('a').each(function() {
var self = $(this);
var href = self.attr('href');
if (href) {
self.attr('href', href.replace(/[\n\r]/g, ''));
self.attr('href', href.replace(/\s+/g, ''));
}
});
$('#result').text(output.html());
});
如果我运行JSbin并输入一些HTML,结果如下:
输入
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE" />
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width">
<meta name="robots" content="noindex" />
<title>TEST</title>
<style type="text/css">
table td {
</style>
</head>
<body yahoo="fix" style="-ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; margin: 0; min-height: 1000px; padding: 0; width: 100%; background:#ffffff;" bgcolor="#FFFFFF">
<div>test</div>
</body>
</html>
输出
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE">
<meta name="format-detection" content="telephone=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width">
<meta name="robots" content="noindex">
<title>TEST</title>
<style type="text/css">
table td {
</style>
<div>test</div>
如您所见,HTML 标记、head 标记和 body 标记丢失了。尽管里面的所有内容都保留了下来。
【问题讨论】:
-
不清楚你在问什么或预期的输出是什么。请自行发布所有相关代码并提供预期结果
标签: javascript jquery html