잡동사니

반응형

질문

페이지가로드 될 때 그 위에 h2 요소의 값이있는 제목 속성이 자동으로 할당되도록 요소에 제목 속성을 동적으로 할당하는 방법이 있습니까?

jQuery / javascript로 가능하다고 생각하지만 방법을 잘 모르겠습니다.

내가 시작한 코드는 다음과 같습니다.

<a><h2>Website</h2></a>

<div class="indent">
 1st Div<br><br>
  <div class="contentbox">
  Content of div with a class of contentbox, this div should dynamically be assign with the attribute of title that has the value of the h2 element that was on top of it. For this instance, it's <b>title="Website"</b>.
  </div>
  
</div>

<a><h2>Portal</h2></a>

<div class="indent">
 2nd Div<br><br>
  <div class="contentbox">
  Content of div with a class of contentbox, this div should dynamically be assign with the attribute of title that has the value of the h2 element that was on top of it. For this instance, it's <b>title="Portal"</b>
  </div>
  
</div>

<a><h2>Stackoverflow</h2></a>

<div class="indent">
 3rd Div<br><br>
  <div class="contentbox">
  Content of div with a class of contentbox, this div should dynamically be assign with the attribute of title that has the value of the h2 element that was on top of it. For this instance, it's <b>title="Stackoverflow"</b>
  </div>
  
</div>

jsfiddle : https://jsfiddle.net/Rgohing/1yrzhpxw/19/

미리 감사드립니다. 도움을 주시면 감사하겠습니다.


답변1

필요한 코드는 HTML의 구조에 따라 크게 달라 지므로 다음과 같이 가정했습니다.

  • < div class = "contentbox"> 는 항상 container에 있습니다 (이 예에서는 < div class = "indent" 그러나 코드는 class에 관계없이 작동합니다.)
  • < h2 > 는 항상 < a > 태그로 둘러싸여 있습니다.

이를 기반으로 제목을 가져 오는 데 필요한 jQuery는 다음과 같습니다.

$(function() {
    $('div.contentbox').attr('title', function() {    
        return $(this).parent().prevAll("a:first").text();
    });
});

다음과 같이 작동합니다.

  1. contentbox class가있는 각 div에 대해 ...
  2. 이 코드는 부모를 가져옵니다 (예 : indent class가있는 container div) ...
  3. 그런 다음 < a > 태그 인 첫 번째 항목을 찾을 때까지 이전 형제를 모두 가져옵니다.
  4. 포함 된 텍스트 (실제로 표제 텍스트)를 반환합니다.
  5. 반환 된 값은 contentbox class가있는 div의 title 으로 추가됩니다.

여기에 제목 텍스트를 콘솔에 출력하는 작업 snippet이 있으므로 올바른 텍스트를 가져 오는지 알 수 있습니다.



답변2

javascript를 사용하여이 작업을 수행 할 수도 있습니다. indent div 안에 h2 태그를 추가하기 만하면됩니다. 아래는 완전히 작동하는 코드입니다.

<div class="indent">
    <a>
        <h2>Website</h2>
    </a>
    1st Div<br><br>
    <div class="contentbox">
        Content of div with a class of contentbox, this div should dynamically be assign with the attribute of title
        that has the value of the h2 element that was on top of it. For this instance, it's <b>title="Website"</b>.
    </div>

</div>



<div class="indent">
    <a>
        <h2>Portal</h2>
    </a>
    2nd Div<br><br>
    <div class="contentbox">
        Content of div with a class of contentbox, this div should dynamically be assign with the attribute of title
        that has the value of the h2 element that was on top of it. For this instance, it's <b>title="Portal"</b>
    </div>

</div>



<div class="indent">
    <a>
        <h2>Stackoverflow</h2>
    </a>
    3rd Div<br><br>
    <div class="contentbox">
        Content of div with a class of contentbox, this div should dynamically be assign with the attribute of title
        that has the value of the h2 element that was on top of it. For this instance, it's
        <b>title="Stackoverflow"</b>
    </div>

</div>
<script>
    let contentbox = document.querySelectorAll('.contentbox');
    for (i = 0; i < contentbox.length; i++) {
        contentbox[i].setAttribute('title', contentbox[i].parentElement.firstElementChild.innerText);
    }
</script>


답변3

요소의 html / text를 title 속성에 할당하기 만하면됩니다. 아래와 같이

$('h2').each(function(){
    var val = $(this).text();
    $(this).parent('a').siblings('.indent').children('.contentbox').attr("title", val);
})


답변4

가장 좋은 방법은 소스에서 변경하는 것입니다. 즉, HTML 또는 HTML을 생성하는 코드를 편집하는 것입니다. 클라이언트 측 접근 방식은 최후의 수단이어야합니다.

div.indent 요소에 속성을 추가하고 싶다고 가정 해 보겠습니다. jQuery를 사용하여 title 속성을 추가하는 코드는 다음과 같습니다.

$('div.indent').attr('title', function() {
    return $(this).prev().text();
});

그러나 목표가 title 속성을 내부 div 에 추가하는 것이라면 다음과 같이 접근 할 수 있습니다.

$('div.contentbox').attr('title', function() {
    return $(this).closest('div.indent').prev().text();
});



 

 

 

 

출처 : https://stackoverflow.com/questions/62742809/dynamically-assign-a-title-in-an-element-using-the-value-of-h2-element

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band