programing

Twitter 부트스트랩 원격 모달이 매번 동일한 콘텐츠를 표시함

padding 2023. 5. 28. 20:24
반응형

Twitter 부트스트랩 원격 모달이 매번 동일한 콘텐츠를 표시함

트위터 부트스트랩을 사용하고 있습니다. 모달을 지정했습니다.

<div class="modal hide" id="modal-item">

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">x</button>
        <h3>Update Item</h3>
    </div>

    <form action="http://www.website.example/update" method="POST" class="form-horizontal">

    <div class="modal-body">
        Loading content...
    </div>

    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Close</a>
        <button class="btn btn-primary" type="submit">Update Item</button>
    </div>

    </form>

</div>

그리고 그 링크들은

<a href="http://www.website.example/item/1" data-target="#modal-item" data-toggle="modal">Edit 1</a>
<a href="http://www.website.example/item/2" data-target="#modal-item" data-toggle="modal">Edit 2</a>
<a href="http://www.website.example/item/3" data-target="#modal-item" data-toggle="modal">Edit 2</a>

이 링크를 처음 클릭하면 올바른 내용이 표시되지만 다른 링크를 클릭하면 처음 로드된 동일한 내용이 표시되지 않습니다.

나는 그것이 클릭될 때마다 업데이트되기를 원합니다.

추신: 커스텀 jQuery 기능을 통해 쉽게 작동할 수 있지만, 충분히 쉬울 것이고 내가 일을 복잡하게 만드는 것 같아서 네이티브 부트스트랩 모달 원격 기능으로 가능한지 알고 싶습니다.

문제는 두 가지입니다.

첫째, Modal 객체가 인스턴스화되면 다음과 같이 지정된 요소에 지속적으로 연결됩니다.data-target그리고 모달이 전화만 할 것이라는 것을 보여주기 위한 후속 전화.toggle()위에있지업만하않지는습다니트데이값의 .options그래서, 비록.href때 " " " " " " 은 " " 입니다. 모달이 토글될 때 다음 값을 사용합니다.remote업데이트되지 않습니다.대부분의 옵션에서는 개체를 직접 편집하여 이 문제를 해결할 수 있습니다.예를 들어:

$('#myModal').data('bs.modal').options.remote = "http://website.example/item/7";

하지만, 이 경우에는 효과가 없을 거예요, 왜냐하면...

둘째, Modal 플러그인은 원격 리소스를 Modal 객체의 생성자에 로드하도록 설계되었으며, 이는 불행히도 변경이 이루어진 경우에도options.remote다시 로드되지 않습니다.

간단한 해결 방법은 이후 전환하기 전에 Modal 개체를 삭제하는 것입니다.한 가지 방법은 숨김이 끝난 후에 삭제하는 것입니다.

$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
});

참고: 필요에 따라 셀렉터를 조정합니다.이것이 가장 일반적입니다.

플런커

아니면 모달을 시작하는 링크가 이전 것과 다른지 확인하는 것과 같은 좀 더 복잡한 계획을 생각해 볼 수도 있습니다.그렇다면 파괴하고 그렇지 않으면 다시 로드할 필요가 없습니다.

부트스트랩 3의 경우 다음을 사용해야 합니다.

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

하고 Bootstrap 3.1을 .modal-content원격 콘텐츠가 로드되기를 기다리는 동안 깜박임을 방지하기 위해 전체 대화 상자(3.0)가 아니라,

$(document).on("hidden.bs.modal", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});

비원격 모드를 사용하는 경우 위의 코드는 물론 닫히면 해당 콘텐츠를 제거합니다(불량).이러한 모델에 무언가를 추가해야 할 수도 있습니다(예:.local-modal영향을 받지 않습니다.그런 다음 위의 코드를 다음으로 수정합니다.

$(document).on("hidden.bs.modal", ".modal:not(.local-modal)", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});

감사합니다.저는 boostrap.js를 만지작거리기 시작했지만 당신의 대답은 빠르고 깨끗한 해결책입니다.이것이 제 코드에서 사용하게 된 것입니다.

$('#modal-item').on('hidden', function() {
    $(this).removeData('modal');
});

수락된 답변이 저에게 맞지 않아서 자바스크립트로 진행했습니다.

<a href="/foo" class="modal-link">
<a href="/bar" class="modal-link">

<script>
$(function() {
    $(".modal-link").click(function(event) {
        event.preventDefault()
        $('#myModal').removeData("modal")
        $('#myModal').modal({remote: $(this).attr("href")})
    })
})

이것은 부트스트랩 3 FYI와 함께 작동합니다.

$('#myModal').on('hidden.bs.modal', function () {
  $(this).removeData('bs.modal');
});

제 프로젝트는 Yii에 내장되어 있으며 부트스트랩-Yi 플러그인을 사용하므로 이 답변은 Yi를 사용하는 경우에만 관련이 있습니다.

위의 수정은 효과가 있었지만 처음으로 모달이 표시된 후에만 가능했습니다.처음에 빈칸으로 나타났을 때.제가 코드를 시작한 후 Yii가 모드의 숨김 기능을 호출하여 시작 변수를 제거하기 때문이라고 생각합니다.

저는 모달을 시작한 코드 바로 앞에 removeData를 호출하는 것이 효과가 있다는 것을 발견했습니다.제 코드는 이렇게 구성되어 있습니다.

$ ("#myModal").removeData ('modal');
$ ('#myModal').modal ({remote : 'path_to_remote'});

부트스트랩 3.2.0에서는 "on" 이벤트가 문서에 있어야 하며 모달을 비워야 합니다.

$(document).on("hidden.bs.modal", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});

부트스트랩 3.1.0에서 "on" 이벤트는 본문에 있을 수 있습니다.

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

BS 3으로 더 일반적으로 만드는 것은 어떻습니까?모달 DIV의 ID로 "[something]모달"을 사용하면 됩니다.

$("div[id$='modal']").on('hidden.bs.modal',
    function () {
        $(this).removeData('bs.modal');
    }
);

나에게 유일한 작업 옵션은 다음과 같습니다.

$('body').on('hidden.bs.modal', '#modalBox', function () {
    $(this).remove();
});

하며, 저는을부 3용며사, 이은기라는 .popup('popup content')그러면 모달 상자 html이 추가됩니다.

$(this).html(');을 추가하여 가시적인 데이터도 지울 수 있으며, 매우 잘 작동합니다.

원격 URL이 제공되면 jQuery의 로드 방법을 통해 컨텐츠가 한 번 로드되고 .modal-content div에 주입됩니다.data-api를 사용하는 경우 href 속성을 사용하여 원격 소스를 지정할 수도 있습니다.이에 대한 예는 다음과 같습니다.

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

새로운 콘텐츠가 나타날 때까지 오래된 콘텐츠가 표시되고, .html(')이 .modal-content 안에 있는 HTML을 지울 것이기 때문에, 도움이 되기를 바랍니다.

$('#myModal').on('hidden.bs.modal', function () {
   $('#myModal').removeData('bs.modal');
   $('#myModal').find('.modal-content').html('');
});

저는 모달의 상쾌함을 다루는 간단한 토막글을 썼습니다.기본적으로 클릭한 링크를 모달의 데이터에 저장하고 클릭한 링크와 동일한지 확인하여 모달 데이터를 제거합니다.

var handleModal = function()
{
    $('.triggeringLink').click(function(event) {
        var $logsModal = $('#logsModal');
        var $triggeringLink = $logsModal.data('triggeringLink');

        event.preventDefault();

        if ($logsModal.data('modal') != undefined
            && $triggeringLink != undefined
            && !$triggeringLink.is($(this))
        ) {
            $logsModal.removeData('modal');
        }

        $logsModal.data('triggeringLink', $(this));

        $logsModal.modal({ remote: $(this).attr('href') });
        $logsModal.modal('show');
    });
};

부트스트랩 3의 경우 modal.js에서 변경:

$(document)
  .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
  .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open'); })

로.

$(document)
  .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
  .on('hidden.bs.modal', '.modal', function () { 
    $(this).removeData('bs.modal').empty()
    $(document.body).removeClass('modal-open')
  })

(명확함을 위해 간격 추가)

이렇게 하면 모달 컨테이너에서 빈()을 호출하고 데이터를 제거하여 이전 모달 콘텐츠의 원치 않는 플래시를 방지할 수 있습니다.

        $('#myModal').on('hidden.bs.modal', function () {
            $(this).removeData('modal');
        });

이것은 나에게 효과가 있습니다.

다음과 같은 다른 접근 방식이 저에게 효과적입니다.

$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});
$('body').on('hidden.bs.modal', '.modal', function () {
       $("#mention Id here what you showed inside modal body").empty()
});

비우려는 HTML 요소(div, span why).

이것은 나에게 효과가 있습니다.

양식의

<div class="modal fade" id="searchKaryawan" tabindex="-1" role="dialog" aria-labelledby="SearchKaryawanLabel" aria-hidden="true"> <div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title" id="SearchKaryawanLabel">Cari Karyawan</h4>
  </div>
  <div class="modal-body">
    <input type="hidden" name="location">
    <input name="cariNama" type="text" class="form-control" onkeyup="if (this.value.length > 3) cariNikNama();" />
    <div class="links-area" id="links-area"></div>
  </div>
  <div class="modal-footer">
  </div>
</div> </div></div>

대본

<script type="text/javascript">$('body').on('hidden.bs.modal', '.modal', function () {  $(".links-area").empty() }); </script>

links-area는 내가 데이터를 저장하고 삭제해야 하는 영역입니다.

@merv가 수락한 답변의 확장 버전입니다.또한 숨겨진 모달이 원격 소스에서 로드되었는지 확인하고 오래된 콘텐츠가 깜박이지 않도록 삭제합니다.

$(document).on('hidden.bs.modal', '.modal', function () {
  var modalData = $(this).data('bs.modal');

  // Destroy modal if has remote source – don't want to destroy modals with static content.
  if (modalData && modalData.options.remote) {
    // Destroy component. Next time new component is created and loads fresh content
    $(this).removeData('bs.modal');
    // Also clear loaded content, otherwise it would flash before new one is loaded.
    $(this).find(".modal-content").empty();
  }
});

https://gist.github.com/WojtekKruszewski/ae86d7fb59879715ae1e6dd623f743c5

부트스트랩 버전 3.3.2에서 테스트됨

  $('#myModal').on('hide.bs.modal', function() {
    $(this).removeData();
  });

행운을 빕니다.

$('#myModal').on('hidden.bs.modal', function () {
    location.reload();
});

언급URL : https://stackoverflow.com/questions/12286332/twitter-bootstrap-remote-modal-shows-same-content-every-time

반응형