Как я могу изменить значение типа (ld + json) с помощью javascript в метке html? - PullRequest
0 голосов
/ 26 октября 2019

Я использую javascript для изменения «application / ld + json» в метке html-сценария, но я не могу выбрать значение json и изменить его с помощью необработанного js.

hexo 3.9
os:Linux 4.4.0-18362-Microsoft linux x64
узел: 13.0.1

<script id="myjsonid" type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "mainEntityOfPage": "<%- config.url + url_for(path) %>",
        "headline": "<%- page.title %>",
        "datePublished": "<%= page.date %>",
        "dateModified": "<%= page.updated %>",
        "image": "<%= page.thumbnail %>",
        "author": {
            "@type": "Person",
            "name": "<%= config.author %>",
            "image": {
                "@type": "ImageObject",
                "url": "<%= theme.img.avatar %>"
            },
            "description": "<%- theme.uiux.slogan %>"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<%= config.title %>",
            "logo": {
                "@type": "ImageObject",
                "url": "<%= theme.head.high_res_favicon %>"
            }
        },
        "keywords": "<% if(page.tags && page.tags.each) { page.tags.each(function(tag) { %><%- tag.name + ',' %><% })} %><%= theme.head.keywords %>",
        "description": "<% if(page.description) { %><%= page.description %><% } else if(page.excerpt){ %><%= strip_html(page.excerpt).replace(/^s*/, '').replace(/s*$/, '') %><% } else if (config.description){ %><%= config.description %><% } %>"
    }
</script>
<script>
    roundsum = Math.round(Math.random()*"<%= theme.thumbnail.random_amount %>"+1);
    testvar = document.getElementById("myjsonid");
</script>

тествар установлен, позже, я пытаюсь

document.getElementById("myjsonid")["firstChild"]

вывод веб-консоли

#text "
    {
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "mainEntityOfPage": "https://blog.tinyume.com/archives/material-geng-duo-xin-xi.html",
        "headline": "让 Material 文章更加人性化",
        "datePublished": "Tue Oct 01 2019 23:10:21 GMT+0800",
        "dateModified": "Sat Oct 26 2019 14:35:20 GMT+0800",
        "image": "",
        "author": {
            "@type": "Person",
            "name": "黯梦萦辰",
            "image": {
                "@type": "ImageObject",
                "url": "https://cdn.jsdelivr.net/gh/iyume/static/hexo-blog/img/avatar.png"
            },
            "description": "仰望半月的夜空"
        },
        "publisher": {
            "@type": "Organization",
            "name": "黯梦萦辰",
            "logo": {
                "@type": "ImageObject",
                "url": "https://cdn.jsdelivr.net/gh/iyume/static/hexo-blog/img/avatar.png"
            }
        },
        "keywords": "黯梦萦辰,iyume,tinyume,博客",
        "description": "给 Material 文章页添加字数统计、阅读时长和分类标签"
    }
"

но теперь я не знаю, что делать, я пропускаю некоторые документы API?

1 Ответ

1 голос
/ 26 октября 2019

firstChild дает вам текстовый узел с текстом скрипта. Вы можете использовать его свойство nodeValue ( spec , MDN ) для получения и установки текста:

const script = document.getElementById("myjsonid");
script.firstChild.nodeValue = '{"foo": 1}'; // Completely replace it
console.log(script.firstChild.nodeValue);

Live Пример:

const script = document.getElementById("myjsonid");
script.firstChild.nodeValue = '{"foo": 1}'; // Completely replace it
console.log(script.firstChild.nodeValue);
<script id="myjsonid" type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "mainEntityOfPage": "<%- config.url + url_for(path) %>",
        "headline": "<%- page.title %>",
        "datePublished": "<%= page.date %>",
        "dateModified": "<%= page.updated %>",
        "image": "<%= page.thumbnail %>",
        "author": {
            "@type": "Person",
            "name": "<%= config.author %>",
            "image": {
                "@type": "ImageObject",
                "url": "<%= theme.img.avatar %>"
            },
            "description": "<%- theme.uiux.slogan %>"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<%= config.title %>",
            "logo": {
                "@type": "ImageObject",
                "url": "<%= theme.head.high_res_favicon %>"
            }
        },
        "keywords": "<% if(page.tags && page.tags.each) { page.tags.each(function(tag) { %><%- tag.name + ',' %><% })} %><%= theme.head.keywords %>",
        "description": "<% if(page.description) { %><%= page.description %><% } else if(page.excerpt){ %><%= strip_html(page.excerpt).replace(/^s*/, '').replace(/s*$/, '') %><% } else if (config.description){ %><%= config.description %><% } %>"
    }
</script>

Вы также можете использовать textContent ( spec , MDN ) или innerText (spec , MDN ) на самом элементе script:

const script = document.getElementById("myjsonid");
script.firstChild.nodeValue = '{}'; // Completely replace it
console.log(script.firstChild.nodeValue);

Live Пример:

const script = document.getElementById("myjsonid");
script.textContent = '{"foo": 1}'; // Completely replace it
console.log(script.firstChild.nodeValue);
script.innerText = '{"foo": 2}'; // Completely replace it
console.log(script.firstChild.nodeValue);
<script id="myjsonid" type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "mainEntityOfPage": "<%- config.url + url_for(path) %>",
        "headline": "<%- page.title %>",
        "datePublished": "<%= page.date %>",
        "dateModified": "<%= page.updated %>",
        "image": "<%= page.thumbnail %>",
        "author": {
            "@type": "Person",
            "name": "<%= config.author %>",
            "image": {
                "@type": "ImageObject",
                "url": "<%= theme.img.avatar %>"
            },
            "description": "<%- theme.uiux.slogan %>"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<%= config.title %>",
            "logo": {
                "@type": "ImageObject",
                "url": "<%= theme.head.high_res_favicon %>"
            }
        },
        "keywords": "<% if(page.tags && page.tags.each) { page.tags.each(function(tag) { %><%- tag.name + ',' %><% })} %><%= theme.head.keywords %>",
        "description": "<% if(page.description) { %><%= page.description %><% } else if(page.excerpt){ %><%= strip_html(page.excerpt).replace(/^s*/, '').replace(/s*$/, '') %><% } else if (config.description){ %><%= config.description %><% } %>"
    }
</script>

В комментарии вы сказали, что хотите изменить одну конкретную часть структуры. Для этого используйте JSON.parse в строке, чтобы получить дерево объектов для JSON, внесите изменения в это дерево, а затем используйте JSON.stringify, чтобы получить строку JSON для обратной записи в элемент script:

const script = document.getElementById("myjsonid");
const obj = JSON.parse(script.firstChild.nodeValue);
obj.image = "***THIS IS THE UPDATE***";
script.firstChild.nodeValue = JSON.stringify(obj);
console.log(script.firstChild.nodeValue);

Live Пример:

const script = document.getElementById("myjsonid");
const obj = JSON.parse(script.firstChild.nodeValue);
obj.image = "***THIS IS THE UPDATE***";
script.firstChild.nodeValue = JSON.stringify(obj);
console.log(script.firstChild.nodeValue);
<script id="myjsonid" type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "mainEntityOfPage": "<%- config.url + url_for(path) %>",
        "headline": "<%- page.title %>",
        "datePublished": "<%= page.date %>",
        "dateModified": "<%= page.updated %>",
        "image": "<%= page.thumbnail %>",
        "author": {
            "@type": "Person",
            "name": "<%= config.author %>",
            "image": {
                "@type": "ImageObject",
                "url": "<%= theme.img.avatar %>"
            },
            "description": "<%- theme.uiux.slogan %>"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<%= config.title %>",
            "logo": {
                "@type": "ImageObject",
                "url": "<%= theme.head.high_res_favicon %>"
            }
        },
        "keywords": "<% if(page.tags && page.tags.each) { page.tags.each(function(tag) { %><%- tag.name + ',' %><% })} %><%= theme.head.keywords %>",
        "description": "<% if(page.description) { %><%= page.description %><% } else if(page.excerpt){ %><%= strip_html(page.excerpt).replace(/^s*/, '').replace(/s*$/, '') %><% } else if (config.description){ %><%= config.description %><% } %>"
    }
</script>
...