我正在尝试设置包含HTML表格的页面。您可以单击表格上的任何一行来拉出具有不同图像的模态。图像URL将作为data-id存储在标记中,因为我必须在浏览器中执行所有这些操作,并且没有服务器的调用。
我有以下代码来设置我的模态。单独地,$(this).data('chi')获取data-chi id,即图像url。我如何在.html()jQuery方法中的HTML中使用它?我尝试了各种各样的逃脱,但无法弄明白。
$('#orderDetails').html($("<b> Order Id selected: <img src=\'\$(this).data('chi')\' alt=\"Smiley face\">" + '</b>'));
$('#orderModal').modal('show');
链接到JSFiddle - https://jsfiddle.net/rHHmz/171/
答案 0 :(得分:1)
我认为最好的方法是先在变量中保存data-chi
属性,然后在字符串连接中使用它,例如:
var chi = $(this).data('chi');
$('#orderDetails').html($("<b> Order Id selected: <img src='"+chi+"' alt=\"Smiley face\">" + '</b>'));
答案 1 :(得分:1)
使用字符串连接
$(function() {
var $orderModal = $('#orderModal').modal({
keyboard: true,
backdrop: "static",
show: false,
});
$('.table-striped tr[data-id]').on('click', function() {
$orderModal.html('<b> Order Id selected: <img src="' + $(this).data('chi') + '" alt="Smiley face "></b>');
$orderModal.modal('show');
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" />
<h1>Orders</h1>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Customer</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr data-id="1" data-chi="//placehold.it/64X64&text=1">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-id="2" data-chi="//placehold.it/64X64&text=2">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-id="3" data-chi="https://upload.wikimedia.org/wikipedia/en/thumb/6/6e/JMPlogo.png/250px-JMPlogo.png" data-hello="bye">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
</tbody>
</table>
<div id="orderModal" class="modal hide fade" role="dialog" aria-labelledby="orderModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3>Order</h3>
</div>
<div id="orderDetails" class="modal-body"></div>
<div id="orderItems" class="modal-body"></div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
&#13;
答案 2 :(得分:0)
在你的JSFiddle中清理,所以JS现在读到:
$(function () {
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show: false,
});
$(".table-striped").find('tr[data-id]').on('click', function (e) {
$('#orderDetails').html("<b> Order Id selected: <img src=\"" + $(e.target).parent().data('chi') + "\" alt=\"Smiley face\"></b>");
$('#orderModal').modal('show');
});
});
基本上,为了获得触发事件的内容,您必须将事件对象(上面的e
)传递给回调,然后在dom中触发它。在这种情况下,它会排到行,因为用户将点击表格中的给定<td>
,而<tr>
属性data-id
是其父级。