Как передать переменную в модал в Bootstrap 3 - PullRequest
3 голосов
/ 24 февраля 2020

Я уже несколько дней бьюсь над этим. Я пробовал много разных решений, и ни одно из них не работает для меня. Затем я перешел по следующей ссылке, и, похоже, это именно то, что я ищу. https://codepen.io/Oza94/pen/ZbERWy Я скопировал источник точно на мой локальный хост, а также на мой домашний домен. Модели открываются, но данные «Troudbal Troudbal» не отображаются на моем сервере, как это происходит в примере с кодом. Кто-нибудь может помочь?

<!DOCTYPE html>
<html lang="en">

<head>

  <title>Pass Modal Vars</title>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="author" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

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

  <script>
    // data-* attributes to scan when populating modal values
    var ATTRIBUTES = ['myvalue', 'myvar', 'bb'];

    $('[data-toggle="modal"]').on('click', function(e) {
      // convert target (e.g. the button) to jquery object
      var $target = $(e.target);
      // modal targeted by the button
      var modalSelector = $target.data('target');

      // iterate over each possible data-* attribute
      ATTRIBUTES.forEach(function(attributeName) {
        // retrieve the dom element corresponding to current attribute
        var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
        var dataValue = $target.data(attributeName);

        // if the attribute value is empty, $target.data() will return undefined.
        // In JS boolean expressions return operands and are not coerced into
        // booleans. That way is dataValue is undefined, the left part of the following
        // Boolean expression evaluate to false and the empty string will be returned
        $modalAttribute.text(dataValue || '');
      });
    });
  </script>
</head>

<body>

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" data-myvalue="trouducul" data-myvar="bisbis">
      Launch demo modal 1
      </button>

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" data-myvalue="troudbal" data-bb="troudbal">
      Launch demo modal 2
      </button>


  <!-- Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <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="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">
          <span id="modal-myvalue"></span> <span id="modal-myvar"></span> <span id="modal-bb"></span>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
</body>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

</html>

Ответы [ 2 ]

1 голос
/ 24 февраля 2020

Да, это возможно с помощью Bootstrap3 с помощью предопределенного модального метода, такого как $('#myModal').on('show.bs.modal', function(e) {...}).
Do c: https://getbootstrap.com/docs/3.3/javascript/#modals-события

Надеюсь, приведенный ниже фрагмент поможет вам много.

// data-* attributes to scan when populating modal values
var attributesArray = ['myvalue', 'myvar', 'bb'];
// This event fires immediately when the show instance method is called.	
$('#myModal').on('show.bs.modal', function(e) {
  // Get modal id
  var $target = e.target.id;
  // Get target values of clicked button
  var $relatedTarget = e.relatedTarget;
  // Iterate over each possible data-* attribute
  attributesArray.forEach(function(attributeName){
    $('#'+$target+ ' #modal-'+attributeName).text($($relatedTarget).data(attributeName) || '');
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<br><br>
<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" data-myvalue="trouducul" data-myvar="bisbis">
        Launch demo modal 1
      </button>
      <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" data-myvalue="troudbal" data-bb="troudbal">
        Launch demo modal 2
      </button>
     </div>
   </div>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
   <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="myModalLabel">Modal title</h4>
    </div>
    <div class="modal-body">
      <h4>
       <span id="modal-myvalue"></span>
       <span id="modal-myvar"></span>
       <span id="modal-bb"></span>
      </h4>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
   </div>
  </div>
</div>
0 голосов
/ 24 февраля 2020

пожалуйста, попробуйте следующее,

Javascript part,
  `<script type="text/javascript">
   $(document).on("click", ".open-modal", function () {
   var x = new Date(); 
   var myHeading = "<p>I Am Added Dynamically </p>";
   $("#modal-body").html(myHeading + x);     
   $('#modal').modal('show');
   });

`

HTML часть;

   `<!----modal starts here--->
    <div id="modal" class="modal fade" role='dialog'>
    <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria- 
     hidden="true">×</button>
            <h4 class="modal-title"> Modal Demo</h4>
        </div>
        <div class="modal-body" id= "modal-body">
            <p>Here the description starts here........</p>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data- 
          dismiss="modal">Close</button>
         </div>
      </div>
    </div>
  </div>
 <!--Modal ends here--->

  <button type="button" class="btn btn-info btn-lg open-modal" >Click Here To Open Modal</button>`
...