페이지를 새로고침하면 JS 코드가 작동하지 않습니다

안녕하세요,

이 문제를 어떻게 해결할 수 있을까요? 도와주세요 :pray:

<script>
let intervalId = setInterval(() => {
  const tags = document.querySelectorAll('.discourse-tag');
  if (tags.length > 0) {
    Array.prototype.forEach.call(tags, (tag) => {
      const tagClone = tag.cloneNode(true);
      tagClone.style.fontSize = 'var(--font-down-2)';
      tagClone.style.backgroundColor = '#1f1f33';
      tagClone.style.margin = '1px';
      tagClone.style.borderRadius = '7px';
      tagClone.style.padding = '2px 8px';
      const title = tag.closest('.main-link').querySelector('.title');
      title.parentNode.insertBefore(tagClone, title);
      tag.remove();
    });
    clearInterval(intervalId);
  }
}, 100);
</script>

왜 CSS 스타일을 적용하는 대신 JS로 이렇게 하고 있나요?

태그가 CSS로 원하는 위치에 배치되지 않았습니다

어떻게요? 스타일을 수동으로 주입하면 CSS 변경과 동일한 결과가 나와야 할 텐데요.

저는 전문가가 아닙니다. 제가 찾을 수 있는 코드로만 수정을 할 수 있을 뿐, 처음부터 코드를 작성하는 것은 불가능합니다.
제 포럼을 확인해 보실 수 있습니다.
https://pvpfarm.com

제 우선순위는 항상 CSS로 편집하는 것입니다. 제 첫 번째 JS 코드입니다.

아래와 같은 것을 원하시는 것 같습니다:

  1. topic-list-before-status 플러그인 아웃렛을 사용하여 태그를 이동하세요.
<script type="text/x-handlebars" data-template-name="/connectors/topic-list-before-status/tag.raw">
  {{discourse-tags context.topic mode="list" tagsForUser=context.tagsForUser}}
</script>
  1. CSS를 사용하여 원래의 태그를 숨기고 스타일을 지정하세요 (조정이 필요할 수 있습니다)
.link-bottom-line .discourse-tags {
    display: none;
}

.link-top-line .discourse-tags {
    column-gap: 5px;
    vertical-align: text-top;
    
    .discourse-tag {
        font-size: var(--font-down-2);
        border-radius: 7px;
        padding: 2px 8px;
        background-color: #1f1f33;
    }

    .discourse-tag::after {
        content: '' !important;
        margin: none !important;
    }
}

도와주셔서 감사합니다. :pray:
지금 이 코드를 사용 중이고 정상적으로 작동합니다.

<script>
function moveTagsToTitle() {
    const mainLinks = document.querySelectorAll('.main-link');
    mainLinks.forEach(mainLink => {
        const discourseTags = mainLink.querySelector('.discourse-tags');
        const titleElement = mainLink.querySelector('.title');

        if (discourseTags && titleElement) {
            const tags = discourseTags.querySelectorAll('.discourse-tag');

            tags.forEach(tag => {
                const tagSpan = document.createElement('span');
                tagSpan.className = 'discourse-tag box';
                tagSpan.textContent = tag.textContent;
                tagSpan.style.fontSize = 'var(--font-down-2)';
                tagSpan.style.borderRadius = '10px';
                tagSpan.style.border = '1px solid #444460';
                tagSpan.style.backgroundColor = '#1f1f33';
                tagSpan.style.color = 'white';
                tagSpan.style.margin = '2px';
                tagSpan.style.padding = '2px 8px';
                tagSpan.style.display = 'inline-block';
                tagSpan.style.overflow = 'hidden';
                tagSpan.style.whiteSpace = 'nowrap';
                tagSpan.style.textOverflow = 'ellipsis';
                tagSpan.style.verticalAlign = 'middle';
                tagSpan.style.marginRight = '5px';
                titleElement.insertBefore(tagSpan, titleElement.firstChild);
            });

            if (discourseTags.parentNode) {
                discourseTags.parentNode.removeChild(discourseTags);
            }
        }
    });
}

window.addEventListener('load', moveTagsToTitle);
const observer = new MutationObserver(moveTagsToTitle);
const targetNode = document.body;
const observerOptions = {
    childList: true,
    subtree: true
};
observer.observe(targetNode, observerOptions);
</script>

동작한다는 말씀에 기쁩니다. 네, 순수 JavaScript를 사용하는 것도 가능합니다. 하지만 목표를 달성하기 위해 Discourse API와 플러그인 아웃렛을 사용하는 것을 강력히 권장합니다. 더 깔끔하고 변경 사항에 대한 내구성도 좋습니다. :+1:

제 영어 실력이 많은 부분에서 부족합니다.
사이트에 해를 끼칠 수 있는 코드는 원치 않습니다.
예를 들어, 이 JS 코드가 사이트를 느리게 만드는 것은 원치 않습니다. (희망합니다 :grin:)
도와주셔서 감사합니다 :heart:

그렇게 하려는 건 좋은 방법이 아니라고 생각해요.

뭘 하려고 하는 거예요?

태그를 주제 제목 왼쪽으로 옮겼습니다.
이렇게 하면 작동하긴 하지만, 선택지가 없습니다. CSS로 코드를 작성할 수 없기 때문입니다.
제 사이트를 방문할 수 있습니다. 링크는 위에 작성해 두었습니다.

이전 게시물 #6에서 더 깔끔한 방법을 알려드린 바 있습니다.

이상적으로는 템플릿을 직접 업데이트하는 것이 좋지만, 이는 유지보수 및 호환성 문제를 일으킬 수 있으므로 권장하지 않습니다.

주신 코드를 필요한 위치에 업로드했습니다. 하지만 지금처럼 작동하지는 않았습니다.

주신 코드가 현재 사이트에 활성화되어 있습니다. 확인해 주실까요?

문제를 찾았습니다!

이상하네요. 카테고리 페이지의 “최신 주제 목록” 템플릿에는 플러그인 아웃렛이 없습니다. :thinking:

https://github.com/discourse/discourse/blob/main/app/assets/javascripts/discourse/app/components/latest-topic-list-item.hbs#L13

네, 맞습니다. 불행히도 제 코드는 해당 페이지에서 작동하지 않습니다.

다만 /latest 페이지에서는 작동해야 합니다.

제 로컬 discourse에서 보이는 것

내가 만약 코드를 쓴다면, CSS로 쓸 거야.
아니면 영웅이 와서 나를 도와줄 거야. :smiley: