简体   繁体   English

在Javascript中将自关闭标签更改为显式标签的方法?

[英]Method to change self-closing tags to explicit tags in Javascript?

Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript?是否存在可以将自关闭标签转换为 Javascript 中的显式标签的方法或函数? For example:例如:

<span class="label"/>

converted to :转换成 :

<span class ="label"></span>

I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly.我想从 iframe 复制一个新的 HTML 到主页的外层 HTML,因为生成的新 HTML 包含自关闭标签,外层 HTML 无法识别它们,然后不会改变,页面也不会显示正确。 But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.但是当格式是标准的,也就是带有非自闭标签的时候,outerHTML 会采用新的HTML,页面显示完美。这就是我想改变标签的原因。


And this html is in a string这个 html 在一个字符串中

In fact, I don't want to parse HTML, I just want to find the "< span.../>"and replace it with "< span...>< /span>"其实我不想解析HTML,我只想找到“<span.../>”并替换为“<span...></span>”

try this to replace all self closing tags out of your string (xml/html)试试这个来替换你的字符串中的所有自结束标签(xml/html)

function removeSelfClosingTags(xml) {
    var split = xml.split("/>");
    var newXml = "";
    for (var i = 0; i < split.length - 1;i++) {
        var edsplit = split[i].split("<");
        newXml += split[i] + "></" + edsplit[edsplit.length - 1].split(" ")[0] + ">";
    }
    return newXml + split[split.length-1];
}

我会使用正则表达式:

var spansFixed = htmlString.replace(/<span(.*)\\/>/g, '<span$1></span>');

Thanks all, I finally use the silly method to change the self-closing tags, maybe it'll help someone like me:谢谢大家,我终于用傻逼的方法改了自闭标签,说不定对我这样的人有帮助:

var splitSpan = textHTML.split(">");
var i=0;
for(i=0;i<splitSpan.length-1;i++){
    var lengthSpan = splitSpan[i].length;
    var subSpan = splitSpan[i].substring(1,5);
    var endSpan = splitSpan[i].charAt(lengthSpan-1);
    
    if(subSpan=="span" && endSpan=="/")
    {           
        splitSpan[i]=setCharAt(splitSpan[i],lengthSpan-1,'>');
        splitSpan[i]=splitSpan[i]+"</span>";
    }
    else
    {
        splitSpan[i]=splitSpan[i]+">";
    }
}

function setCharAt(str,index,chr) {
    if(index > str.length-1) return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

I can't think of any need for this, as they will automatically be converted by the browser.我想不出有什么需要,因为它们会被浏览器自动转换。 This can be demonstrated by:这可以通过以下方式证明:

var div = document.createElement('div');
div.innerHTML = '<span/>';
var span = div.getElementsByTagName('span')[0];
span.innerHTML = 'hello';
alert(span.innerHTML);

Edit: It seems this will only work only in XML mode.编辑:这似乎只适用于 XML 模式。

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

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