如何使用jQuery打开Bootstrap模式窗口?

时间:2012-11-01 18:52:19

标签: javascript jquery twitter-bootstrap

我正在使用Twitter Bootstrap模态窗口功能。当有人点击我表单上的提交时,我想在点击表单中的“提交按钮”时显示模态窗口。

<form id="myform" class="form-wizard">
    <h2 class="form-wizard-heading">BootStap Wizard Form</h2>
    <input type="text" value=""/>
    <input type="submit"/>
</form>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

jQuery的:

$('#myform').on('submit', function(ev) {
    $('#my-modal').modal({
        show: 'false'
    }); 


    var data = $(this).serializeObject();
    json_data = JSON.stringify(data);
    $("#results").text(json_data); 
    $(".modal-body").text(json_data); 

    // $("#results").text(data);

    ev.preventDefault();
});

16 个答案:

答案 0 :(得分:1176)

Bootstrap有一些可以在模态上手动调用的函数:

$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');

您可以在此处查看更多内容:Bootstrap modal component

特别是methods section

所以你需要改变:

$('#my-modal').modal({
    show: 'false'
}); 

为:

$('#myModal').modal('show'); 

如果您想制作自己的自定义弹出窗口,请参阅其他社区成员的推荐视频:

https://www.youtube.com/watch?v=zK4nXa84Km4

答案 1 :(得分:77)

此外,您可以使用via data属性

<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>

在这种特殊情况下,您不需要编写javascript。

您可以在此处查看更多内容:http://getbootstrap.com/2.3.2/javascript.html#modals

答案 2 :(得分:67)

大多数情况下,当$('#myModal').modal('show');无效时,由于包含jQuery两次而导致这种情况。包括jQuery 2次使模态不起作用。

删除其中一个链接,使其再次运行。

此外,一些插件也会导致错误,在这种情况下添加

jQuery.noConflict(); 
$('#myModal').modal('show'); 

答案 3 :(得分:16)

使用jQuery选择器调用模态方法(不传递任何参数)。

以下是示例:

$('#modal').modal();

答案 4 :(得分:12)

如果使用链接的onclick函数通过jQuery调用模态,则“href”不能为空。

例如:

... ...
<a href="" onclick="openModal()">Open a Modal by jQuery</a>
... ...
... ...
<script type="text/javascript">

function openModal(){

    $('#myModal').modal();
}       
</script>

模态无法显示。 正确的代码是:

<a href="#" onclick="openModal()">Open a Modal by jQuery</a>

答案 5 :(得分:9)

在此处查看完整的解决方案:

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_modal_show&stacked=h

确保按要求的顺序放置库以获得结果:

1-首先bootstrap.min.css 2- jquery.min.js 3- bootstrap.min.js

(换句话说,必须在bootstrap.min.js之前调用jquery.min.js)

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script> 

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

答案 6 :(得分:9)

以下是文档准备就绪后如何加载引导程序警报。只需添加

即可
 $(document).ready(function(){
   $("#myModal").modal();
});

我在W3Schools上做了demo

&#13;
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Here is how to load a bootstrap modal as soon as the document is ready </h2>
  <!-- Trigger the modal with a button -->


  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
  
</div>

<script>
$(document).ready(function(){
   $("#myModal").modal();
});
</script>

</body>
</html>
&#13;
&#13;
&#13;

答案 7 :(得分:5)

我尝试了几种失败的方法,但下面的方法对我来说就像一个魅力:

$('#myModal').appendTo("body").modal('show');

答案 8 :(得分:3)

尝试

$("#myModal").modal("toggle")

使用id myModal打开或关闭模态。

如果上述方法无效,则表示bootstrap.js已被其他一些js文件覆盖。 这是一个解决方案

1: - 将bootstrap.js移到底部,以便覆盖其他js文件。

2: - 确保订单如下

<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Other js files -->
<script src="plugins/jQuery/bootstrap.min.js"></script>

答案 9 :(得分:2)

<form id="myform" class="form-wizard">
    <h2 class="form-wizard-heading">BootStap Wizard Form</h2>
    <input type="text" value=""/>
    <input type="submit" id="submitButton"/>
</form>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

您可以使用下面的代码启动模式。

$(document).ready(function(){
    $("#submitButton").click(function(){
        $("#myModal").modal();
    });
});

答案 10 :(得分:2)

在调用该函数时,尝试使用 jQuery 而不是 $ 符号,就我而言,它可以正常工作,如下所示。

(-> (sqlh/select :*)
    (sqlh/from :event)
    (sqlh/merge-where [:in :field_id field-ids])
    (sqlh/merge-where (cond (not-empty layers) [:in :layer layers]))
    (sqlh/merge-where (make-where-for-timestamp
                        :event_date event-date-from event-date-to))
    (sqlh/merge-where (make-where-for-timestamp
                        :updated_at updated-at-from updated-at-to))
    (sqlh/order-by :field_id :layer [:event_date :desc])
    sql/format)
=>
["SELECT * FROM event WHERE ((field_id in (?)) AND (layer in (?, ?, ?))) ORDER BY field_id, layer, event_date DESC"
 "1325629"
 "fha.true-color"
 "fha.abs"
 "fha.rank"]

jQuery.noConflict(); ,因为当jQuery('#myModal')。modal('show');不起作用,这是由于两次包含jQuery引起的。包括jQuery 2次使模态不起作用。在这种情况下,它将解决问题,就像我的情况一样。

此外,您可以转到此链接

Bootstrap Model Window Not Showing by Calling Through JQuery

答案 11 :(得分:0)

尝试一下

  

myModal1是模态的ID

$('#myModal1')。modal({show:true});

答案 12 :(得分:0)

<script type="text/javascript">
    $(function () {
        $("mybtn").click(function () {
            $(""#my-modal").modal("show");
        });
    });
</script>

答案 13 :(得分:0)

Bootstrap 4.3 -更多here

$('#exampleModal').modal();
<!-- Initialize Bootstrap 4 -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


<!-- MODAL -->

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
    
      <div class="modal-body">
        Hello world   
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

答案 14 :(得分:0)

尝试一下。对我来说很好。

public static async Task Main()
        {
            
            BlobContainerClient container;
            try
            {
                container = new BlobServiceClient(connectionString).GetBlobContainerClient(containerName);
                await container.CreateIfNotExistsAsync(PublicAccessType.None);

            }
            catch (Exception)
            {
                var msg = $"Storage account not found. Ensure that the environment variable " +
                    " is set to a valid Azure Storage connection string and that the storage account exists.";
                Console.WriteLine(msg);
                return;
            }

            // First, the newsroom chief writes the story notes to the blob
            await SimulateChief();
            Console.WriteLine();

            await Task.Delay(TimeSpan.FromSeconds(2));

            // Next, two reporters begin work on the story at the same time, one starting soon after the other
            var reporterA = SimulateReporter("Reporter A", writingTime: TimeSpan.FromSeconds(12));
            await Task.Delay(TimeSpan.FromSeconds(4));
            var reporterB = SimulateReporter("Reporter B", writingTime: TimeSpan.FromSeconds(4));

            await Task.WhenAll(reporterA, reporterB);
            await Task.Delay(TimeSpan.FromSeconds(2));

            Console.WriteLine();
            Console.WriteLine("=============================================");
            Console.WriteLine();
            Console.WriteLine("Reporters have finished, here's the story saved to the blob:");

            BlobDownloadInfo story = await container.GetBlobClient(blobName).DownloadAsync();

            Console.WriteLine(new StreamReader(story.Content).ReadToEnd());
        }

        private static async Task SimulateReporter(string authorName, TimeSpan writingTime)
        {
            // First, the reporter retrieves the current contents
            Console.WriteLine($"{authorName} begins work");
            var blob = new BlobContainerClient(connectionString, containerName).GetBlobClient(blobName);

            var contents = await blob.DownloadAsync();

            Console.WriteLine($"{authorName} loads the file and sees the following content: \"{new StreamReader(contents.Value.Content).ReadToEnd()}\"");

            // Store the current ETag
            var properties = await blob.GetPropertiesAsync();
            var currentETag = properties.Value.ETag;
            Console.WriteLine($"\"{contents}\" has this ETag: {properties.Value.ETag}");

            // Next, the author writes their story. This takes some time.
            Console.WriteLine($"{authorName} begins writing their story...");
            await Task.Delay(writingTime);
            Console.WriteLine($"{authorName} has finished writing their story");

            try
            {
                // Finally, they save their story back to the blob.
                var story = $"[[{authorName.ToUpperInvariant()}'S STORY]]";
                await uploadDatatoBlob(blob, story);
                Console.WriteLine($"{authorName} has saved their story to Blob storage. New blob contents: \"{story}\"");
            }
            catch (RequestFailedException e)
            {
                // Catch error if the ETag has changed it's value since opening the file
                Console.WriteLine($"{authorName} sorry cannot save the file as server returned an error: {e.Message}");
            }
        }

        private static async Task SimulateChief()
        {
            var blob = new BlobContainerClient(connectionString, containerName).GetBlobClient(blobName);

            var notes = "[[CHIEF'S STORY NOTES]]";
            await uploadDatatoBlob(blob, notes);
            Console.WriteLine($"The newsroom chief has saved story notes to the blob {containerName}/{blobName}");
        }

        private static async Task uploadDatatoBlob(BlobClient blob, string notes)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(notes);
            MemoryStream stream = new MemoryStream(byteArray);
            await blob.UploadAsync(stream, overwrite: true);
        }
await blob.UploadTextAsync(story, null, accessCondition: AccessCondition.GenerateIfMatchCondition(currentETag), null, null);

答案 15 :(得分:0)

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>