programing tip

div의 내용 변경-jQuery

itbloger 2020. 10. 12. 07:19
반응형

div의 내용 변경-jQuery


LINKS 중 하나를 클릭했을 때이 div의 내용을 어떻게 변경할 수 있습니까?

<div align="center" id="content-container">
    <a href="#" class="click cgreen">Main Balance</a>
    <a href="#" class="click cgreen">PayPal</a>
    <a href="#" class="click cgreen">AlertPay</a>
</div>

링크에 대한 .click 이벤트를 구독하고 .html메소드를 사용하여 div의 내용을 변경할 수 있습니다 .

$('.click').click(function() {
    // get the contents of the link that was clicked
    var linkText = $(this).text();

    // replace the contents of the div with the link text
    $('#content-container').html(linkText);

    // cancel the default action of the link by returning false
    return false;
});

그러나이 div의 내용을 바꾸면 할당 한 클릭 핸들러가 삭제됩니다. 이벤트 핸들러를 첨부해야하는 div 내부에 새 DOM 요소를 삽입하려는 경우 새 컨텐츠를 삽입 한 후 .click 핸들러 내에서이 첨부를 수행해야합니다. 이벤트의 원래 선택기가 유지 .delegate되는 경우 처리기를 연결하는 메서드를 살펴볼 수도 있습니다 .


여기서 사용하려는 두 가지 jQuery 함수가 있습니다.

1) click. 이것은 유일한 매개 변수 인 익명 함수를 취하고 요소를 클릭 할 때 실행합니다.

2) html. 이것은 유일한 매개 변수로 html 문자열을 취하고 요소의 내용을 제공된 html로 대체합니다.

따라서 귀하의 경우 다음을 수행하고 싶을 것입니다.

$('#content-container a').click(function(e){
    $(this).parent().html('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

div에있는 모든 내용을 바꾸지 않고 div 에만 콘텐츠 추가 하려면 append다음 을 사용해야합니다 .

$('#content-container a').click(function(e){
    $(this).parent().append('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

새로 추가 된 링크를 클릭했을 때 새 콘텐츠도 추가하려면 이벤트 위임 을 사용해야합니다 .

$('#content-container').on('click', 'a', function(e){
    $(this).parent().append('<a href="#">I\'m a new link</a>');
    e.preventDefault();
});

$('a').click(function(){
 $('#content-container').html('My content here :-)');
});

replacewith () 와 동일하게 시도 할 수 있습니다.

$('.click').click(function() {
    // get the contents of the link that was clicked
    var linkText = $(this).text();

    // replace the contents of the div with the link text
    $('#content-container').replaceWith(linkText);

    // cancel the default action of the link by returning false
    return false;
});

.replaceWith()메서드는 DOM에서 콘텐츠를 제거하고 한 번의 호출로 그 자리에 새 콘텐츠를 삽입합니다.


jQuery를 사용하여 div의 내용을 변경하려면 이것을 시도하십시오.

See more @ Change content of div using jQuery

$(document).ready(function(){
    $("#Textarea").keyup(function(){
        // Getting the current value of textarea
        var currentText = $(this).val();

        // Setting the Div content
        $(".output").text(currentText);
    });
});

Try $('#score_here').html=total;

참고URL : https://stackoverflow.com/questions/7139208/change-content-of-div-jquery

반응형