简体   繁体   English

如何使用jQuery删除重复的元标记?

[英]How to use jquery to remove duplicated meta tag?

For some reasons, my page contains two meta tag sections in the header, and they are the same. 由于某些原因,我的页面的标题中包含两个meta标签部分,它们是相同的。

I can create a jquery code to remove the duplicated one if this meta tag is only one line; 如果此meta标签只有一行,我可以创建一个jquery代码来删除重复的代码; however, my situation is that these meta tags contain 6 lines, like the first part of the following codes showing: 但是,我的情况是这些元标记包含6行,如以下代码的第一部分所示:

(the second part is the duplicated part I want to remove) (第二部分是我要删除的重复部分)

<meta property="fb:app_id" content="123456789">
<meta property="og:site_name" content="MyWebsite">
<meta property="og:url" content="http://ThisIsMyWebsite.com">
<meta property="og:title" content="Duplicated Meta Tag Testing">
<meta property="og:description" content="Test the duplicated meta tags">
<meta property="og:image" content="http://ThisIsMyWebsite.com/show.jpg">

<meta property="fb:app_id" content="123456789">
<meta property="og:site_name" content="MyWebsite">
<meta property="og:url" content="http://ThisIsMyWebsite.com">
<meta property="og:title" content="Duplicated Meta Tag Testing">
<meta property="og:description" content="Test the duplicated meta tags">
<meta property="og:image" content="http://ThisIsMyWebsite.com/show.jpg">

Is there any clear way to find/remove duplicated part?(Keep only one part) 是否有找到/删除重复零件的明确方法?(仅保留一个零件)

Thank you. 谢谢。

Here's one solution, will keep the first one only: 这是一个解决方案,将仅保留第一个解决方案:

var found = {};
$('meta').each(function(){
    var $this = $(this);
    if(found[$this.attr('property')]){
         $this.remove();   
    }
    else{
         found[$this.attr('property')] = true;   
    }
});

You can create a for loop and remove all occurrences of each meta property after the first one. 您可以创建一个for循环,并删除第一个之后的所有meta属性。

var exists = {};
$('meta').each(function () {
    var meta = $(this);
    var property = meta.attr('property');
    if(!property)
        return;

    if (exists[property]) meta.remove();
    else exists[property] = meta;
});

JSFiddle: https://jsfiddle.net/7hwvyphm/ JSFiddle: https ://jsfiddle.net/7hwvyphm/

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

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