小编典典

JavaScript将数据传递到引导模式

spring

这是代码:

<a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>

哪个应该打开:

<div class="modal hide" id="addBookDialog">
    <div class="modal-body">
        <input type="hidden" name="bookId" id="bookId" value=""/>
    </div>
</div>

使用这段代码:

$(document).ready(function () {
    $(".open-AddBookDialog").click(function () {
        $('#bookId').val($(this).data('id'));
        $('#addBookDialog').modal('show');
    });
});

但是,当我单击超链接时,没有任何反应。当我提供超链接时,模式可以很好地打开,但是它不包含任何数据。


阅读 371

收藏
2020-04-25

共2个答案

小编典典

我认为你可以使用jQuery的.on事件处理程序来完成这项工作。

这是你可以测试的小提琴;只需确保在小提琴中尽可能扩展HTML框架,以便你可以查看模式。

HTML

<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<p>&nbsp;</p>


<p>Link 2</p>
<a data-toggle="modal" data-id="ISBN-001122" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<div class="modal hide" id="addBookDialog">
 <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
  </div>
    <div class="modal-body">
        <p>some content</p>
        <input type="text" name="bookId" id="bookId" value=""/>
    </div>
</div>

JAVASCRIPT

$(document).on("click", ".open-AddBookDialog", function () {
     var myBookId = $(this).data('id');
     $(".modal-body #bookId").val( myBookId );
     // As pointed out in comments, 
     // it is unnecessary to have to manually call the modal.
     // $('#addBookDialog').modal('show');
});
2020-04-25
小编典典

如果你使用的是Bootstrap 3.2.0,这是一种更干净的方法。

连结HTML

<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>

模态JavaScript

//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {

    //get data-id attribute of the clicked element
    var bookId = $(e.relatedTarget).data('book-id');

    //populate the textbox
    $(e.currentTarget).find('input[name="bookId"]').val(bookId);
});
2020-04-25