twitter-bootstrap 使用 Pure JavaScript On Click 隐藏 Bootstrap Modal

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46577690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:05:50  来源:igfitidea点击:

Hide Bootstrap Modal using Pure JavaScript On Click

javascripttwitter-bootstrap

提问by Jone Doe

I was working on Bootstrap Pop Up Modals.

我正在研究 Bootstrap 弹出模式。

I have 2 Buttons named Button1& Button2.

我有 2 个名为Button1Button2 的按钮。

&

&

I have 2 Modals named Modal1& Modal2.

我有两个名为Modal1Modal2 的模态。

Note : Button2is inside the Modal1& Button1is on the Web Page.

注:Button2的是里面的Modal1Button1的是对网页。

If I click Button1, Modal1should be Open & If I click Button2that is inside the Modal, then Modal1 should be hide automatically and Modal2 should be shown.

如果我点击Button1Modal1应该是 Open & 如果我点击Modal 里面的Button2,那么 Modal1 应该自动隐藏并且 Modal2 应该被显示。

I am doing it using jQuery Yet & It's working Fine.

我正在使用 jQuery 完成它,但它工作正常。

<script>
$('#button1').click(function()
{
    $('#modal1').modal('hide');
    $('#modal2').modal('show');
});
</script>

Question:

问题:

How I can do it using Pure JavaScript. ???????

我如何使用纯 JavaScript 做到这一点。???????

回答by Nebojsha

Here is workaround I wrote in order to close modal in native Java Script, using DOM manipulation. Bootstrap 4 is used.

这是我编写的解决方法,目的是使用 DOM 操作关闭本机 Java 脚本中的模式。使用引导程序 4。

function closeAllModals() {

    // get modals
    const modals = document.getElementsByClassName('modal');

    // on every modal change state like in hidden modal
    for(let i=0; i<modals.length; i++) {
      modals[i].classList.remove('show');
      modals[i].setAttribute('aria-hidden', 'true');
      modals[i].setAttribute('style', 'display: none');
    }

     // get modal backdrops
     const modalsBackdrops = document.getElementsByClassName('modal-backdrop');

     // remove every modal backdrop
     for(let i=0; i<modalsBackdrops.length; i++) {
       document.body.removeChild(modalsBackdrops[i]);
     }
  }

So this function closes all modals found on page. You can modify it to close one certain modal based on id. This way:

所以这个函数会关闭页面上找到的所有模态。您可以修改它以根据 id 关闭一个特定的模式。这条路:

function closeOneModal(modalId) {

    // get modal
    const modal = document.getElementById(modalId);

    // change state like in hidden modal
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden', 'true');
    modal.setAttribute('style', 'display: none');

     // get modal backdrop
     const modalBackdrops = document.getElementsByClassName('modal-backdrop');

     // remove opened modal backdrop
      document.body.removeChild(modalBackdrops[0]);
  }

So, no clue of jQuery at all

所以,根本不知道 jQuery

回答by Emmanuel Ndukwe

You could just assign an idto a button that would normally dismiss/open the modal, the simulate a click on the button to programmatically dismiss/open a modal.

您可以只id为通常会关闭/打开模态的按钮分配一个,模拟单击按钮以编程方式关闭/打开模态。

e.g - $('#modal1').modal('hide'); $('#modal2').modal('show');would become document.getElementById('modalX').click();

例如 - $('#modal1').modal('hide'); $('#modal2').modal('show');会变成 document.getElementById('modalX').click();

回答by Hamzeen Hameem

Here is a working solution:

这是一个有效的解决方案:

https://codepen.io/hamzeen/pen/MErYgp.

https://codepen.io/hamzeen/pen/MErYgp

You can achieve it without writing any Javascript in your app YET,I couldn't find a way to do it with plain javascript. The data-targetproperty on the anchor tag handles the toggle, check the code below:

你可以实现它没有在您的应用程序编写任何JavaScript YET,我无法找到一种方法与普通的JavaScript来做到这一点。该data-target锚标记财产处理的切换,检查下面的代码:

<a href="#" class="btn btn-lg btn-danger" data-toggle="modal" data-
target="#modal1">Open Modal 1</a>

I found the following from Bootstrap's Javascript Library, probably this helps you!

我从 Bootstrap 的 Javascript 库中找到了以下内容,可能对您有所帮助!

/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript 
requires jQuery");

回答by HariV

You can create a 'modal' element using javascript. The advantage is that you can reuse it. I have created a sample bootstrap modal using javascript. You can modify it to add more features.

您可以使用 javascript 创建一个“模态”元素。优点是可以重复使用。我已经使用 javascript 创建了一个示例引导模式。您可以修改它以添加更多功能。

var Interface = {};
Interface.component = function ( dom ) {
    this.dom = dom;
};
Interface.component.prototype = {
    setId: function ( id ) {
        this.dom.id = id;
        return this;
    }
    // you can add more common functions here
};

Interface.BootstrapModal = function ( id, modalHeading, modalBodyContents, successButtonText, failureButtonText ) {

    var scope = this;
    var dom = document.createElement( 'div' );
    dom.className = 'modal fade';
    dom.id = id;
    dom.role = "dialog";

    var modalDialog = document.createElement( 'div' );
    modalDialog.className = 'modal-dialog';

    var modalContent = document.createElement( 'div' );
    modalContent.className = 'modal-content';

    var modalHeader = document.createElement( 'div' );
    modalHeader.className = 'modal-header';

    var modalHeaderXButton = document.createElement( 'button' );
    modalHeaderXButton.className = 'close';
    modalHeaderXButton.setAttribute("data-dismiss", "modal");
    modalHeaderXButton.innerHTML = '&times';

    var modalHeaderHeading = document.createElement( 'h3' );
    modalHeaderHeading.className = 'modal-title';
    modalHeaderHeading.innerHTML = modalHeading;

    modalHeader.appendChild(modalHeaderXButton);
    modalHeader.appendChild(modalHeaderHeading);

    var modalBody = document.createElement( 'div' );
    modalBody.className = 'modal-body';
    modalBody.appendChild(modalBodyContents);

    var modalFooter = document.createElement( 'div' );
    modalFooter.className = 'modal-footer';

    var modalFooterSuccessButton = document.createElement( 'button' );
    modalFooterSuccessButton.className = 'btn btn-success';
    modalFooterSuccessButton.id = "<GIVE THE ID YOU NEED>";
    //modalFooterSuccessButton.setAttribute("data-dismiss", "modal");
    modalFooterSuccessButton.innerHTML = successButtonText;

    var modalFooterFailureButton = document.createElement( 'button' );
    modalFooterFailureButton.className = 'btn btn-danger';
    modalFooterFailureButton.id = "<GIVE THE ID YOU NEED>";
    modalFooterFailureButton.setAttribute("data-dismiss", "modal");
    modalFooterFailureButton.innerHTML = failureButtonText;

    modalFooter.appendChild(modalFooterSuccessButton);
    modalFooter.appendChild(modalFooterFailureButton);

    modalContent.appendChild(modalHeader);
    modalContent.appendChild(modalBody);
    modalContent.appendChild(modalFooter);
    modalDialog.appendChild(modalContent);

    dom.appendChild(modalDialog);

    modalFooterSuccessButton.addEventListener( 'click', function ( event ) {

        // perform your actions

    } );

    this.dom = dom;
    return this;

};

Interface.BootstrapModal.prototype = Object.create( Interface.component.prototype );
Interface.BootstrapModal.prototype.constructor = Interface.BootstrapModal;

Interface.BootstrapModal.prototype.show = function () {

    $('#' + this.dom.id).modal({backdrop: 'static', keyboard : false});

};

Interface.BootstrapModal.prototype.hide = function () {

    $('#' + this.dom.id).modal('hide');

};

Here I have created the modal element as an object. You can use it like,

在这里,我将模态元素创建为对象。你可以像这样使用它

var modalContent = document.createElement( 'div' );
var m = new Interface.BootstrapModal( 'id', 'modalHeading', modalContent, 'successButtonText', 'cancelButtonText' );
document.getElementById( <SOME ELEMENT> ).appendChild( m.dom );

now m.show()will show the modal and m.hide()will hide the same

现在m.show()将显示模态,而m.hide()将隐藏相同的

This can be used as a general template for bootstrap modals.

这可以用作引导模式的通用模板。

回答by ilya.chepurnoy

Here's how to get modal.hide() (and all other modal methods too!) in pure JS.
You can try it on official docs page, let's take modal documentationas an example here. The catch is, the modal stores a property looking like 'jQuery331042511280243656492' on the modal DOM object. This property has all the modal methods inside! Just open this modal first, then run the code in console.

以下是如何在纯 JS 中获取 modal.hide() (以及所有其他模态方法!)。
您可以在官方文档页面上试用,这里以模态文档为例。问题是,模态在模态 DOM 对象上存储了一个类似于“jQuery331042511280243656492”的属性。这个属性里面有所有的模态方法!只需先打开此模式,然后在控制台中运行代码。

UPDATE: that jQuery object is only attached on 1st opening of the modal, and is present from then on. That means, that we can not '.show()' our modal via this method, unless we've already opened it at least once.

更新:该 jQuery 对象仅在第一次打开模态时附加,并且从那时起就存在。这意味着,我们不能通过这个方法'.show()'我们的模态,除非我们已经至少打开过一次。

    // get reference to the modal. It's 'div.modal', in general
    var modal = document.querySelector('#exampleModalLong');
    // get the key under which the modal's methods are stored.
    var jQueryObj = Object.keys(modal).filter((key) => (key.toString().indexOf('jQuery') !== -1) && modal[key].hasOwnProperty('bs.modal'));
    // ... and close the modal!
    modal[jQueryObj]['bs.modal'].hide();

回答by Nandhi Kumar

Can you try this....

你可以试试这个吗....

function showmodel(){
var Modal1 = document.getElementById("Modal1"); 
Modal1.show(); 
}
function hidemodel1()
{
var Modal1 = document.getElementById("Modal1"); 
var Modal2 = document.getElementById("Modal2"); 
Modal1.hide(); 
Modal2.show(); 
}

Call the above method in button onclick.

在按钮 onclick 中调用上述方法。