将data-id传递给bootstrap模式

时间:2015-10-05 04:33:27

标签: javascript php jquery twitter-bootstrap

我有一个问题是使用bootstrap模式显示data-id。这是我的脚本

 <a class="btn btn-warning btn-minier" href="#modal-form-edit" role="button" data-toggle="modal" data-id="<?php echo $row['product_names']; ?>"><i class="icon-edit bigger-120"></i> Edit</a> &nbsp;

模态

<div id="modal-form-edit" class="modal hide" tabindex="-1">
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="blue bigger">Products</h4>
</div>

<div class="modal-body overflow-visible">
    <div class="row-fluid">

        <div class="vspace"></div>

        <div class="span7">
            <div class="control-group">
                <label class="control-label" for="form-field-username">Product Name</label>

                <div class="controls">
                    <input type="text" name="product_name" placeholder="Product Name" value="" id="product_name" /> 
                </div>
            </div>

JS

$('#modal-form-edit').on('show', function () {
    var product = $(this).data('id');
    $("#product_name").val($(this).data('product'));
})

问题是,data-id未显示值($row['product_names'])

当我改变

var product = $(this).data(id)

var product = "test";

模态显示“测试”。任何帮助我都会感激

1 个答案:

答案 0 :(得分:3)

您需要获取锚标记data-id,而不是使用this

var product = $('a[href="#modal-form-edit"]').data('id');

更新如果您有多个编辑链接,那么要获取点击的锚标记数据ID,您应该使用e.relatedTarget

// using latest bootstrap so, show.bs.modal
$('#modal-form-edit').on('show.bs.modal', function(e) {
  var product = $(e.relatedTarget).data('id');
  $("#product_name").val(product);
});
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

<a class="btn btn-warning btn-minier" href="#modal-form-edit" role="button" data-toggle="modal" data-id="Product 1"><i class="icon-edit bigger-120"></i> Edit</a> &nbsp;
<a class="btn btn-warning btn-minier" href="#modal-form-edit" role="button" data-toggle="modal" data-id="Product 2"><i class="icon-edit bigger-120"></i> Edit</a> &nbsp;
<div id="modal-form-edit" class="modal" tabindex="-1">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="blue bigger">Products</h4>
  </div>

  <div class="modal-body overflow-visible">
    <div class="row-fluid">

      <div class="vspace"></div>

      <div class="span7">
        <div class="control-group">
          <label class="control-label" for="form-field-username">Product Name</label>

          <div class="controls">
            <input type="text" name="product_name" placeholder="Product Name" value="" id="product_name" />
          </div>
        </div>
      </div>
      <!--span7-->
    </div>
  </div>
  <!-- modal-body-->
</div>