简体   繁体   English

如何使用代码而不是单击按钮弹出 javascript 模态

[英]How to popup javascript modal with code instead of button click

I have the following modal:我有以下模式:

<div class="modal fade" id="m_modal_1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

I have the following button that pops up the modal:我有以下弹出模式的按钮:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#m_modal_1"> Launch Modal</button>

Instead of initiating from the button, how do I popup from code?我如何从代码中弹出,而不是从按钮启动? I was thinking something like this:我在想这样的事情:

if(status == 1){

    modal("show");
}

Assuming that you're using Bootstrap (based on the classes).假设您使用的是 Bootstrap(基于类)。

You can use the following:您可以使用以下内容:

$('#m_modal_1').modal('show')

You need to add eventlistener to any element, so once the event is triggered you change classes of the modal element or style.您需要将 eventlistener 添加到任何元素,因此一旦触发事件,您就可以更改模态元素或样式的类。

Assuming you have some element (ie button with classname btn and modal with classname modal)假设您有一些元素(即带有类名 btn 的按钮和带有类名模态的模态)

document.querySelector('.btn').addEventListener('click', () => {
  document.querySelector('.modal').classList.toggle('hidden');
}

And your css can be like this而你的css可以是这样的

.hidden {
  display: none;
  // or
  opacity: 0;
}

I think you are using bootstrap.我认为您正在使用引导程序。 so in your case所以在你的情况下

if(status == 1){

    $("#m_modal_1").modal("show");
}

"show" is a option of modal function. “show”是模态 function 的一个选项。 See more option and usage here https://getbootstrap.com/docs/4.0/components/modal/#options在此处查看更多选项和用法https://getbootstrap.com/docs/4.0/components/modal/#options

Basically it depends on when you want to popup your modal.suppose you want to popup on page ready then,基本上这取决于你什么时候想弹出你的模态。假设你想在页面上弹出准备好,

$(document).ready(function(e){
$(#modal_id).show();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM