我在AJAX调用后收到一些数据并填充列表。
但是当从该列表中单击某个项目时,我想显示一个模式,其中包含有关该项目的信息(如图片,它是多么受欢迎 - 它被点击的次数 - ,作者等)。我可以用丑陋的方式做到这一点:
$('#target').append(
$('<div class = "col-md-4" data-toggle = "modal" data-target = "#myModal" onClick = someFunction(' + someArgument + ')>' + someText + '</div>' +
'<div class = "modal fade" id = "myModal" role = "dialog">' + '<div class = "modal-dialog modal-lg">' +
'<div class = "modal-content"> <div class = "modal-header"> <h4 class = "modal-title">' + someTitle + '</h4></div>' +
'<div class = "modal-body">Description: ' + description + ' Author: ' + author + '<br</br>' +
'<img src = "' + imgSource + '" class = "modal-dialog modal-lg" style = "max-width: 25%;">' +
'<button type = "button" class = "close" data-dismiss = "modal" id = "myModal">×</button>' +
'<div class = "modal-footer"></div></div></div></div></div>'));
这很丑陋,容易出错,难以维护,难以阅读。它能以更优雅的方式完成吗?
答案 0 :(得分:1)
首先,您的代码应该写在show.bs.modal
函数内。
$('#target').on('show.bs.modal', function (e) {
// do something...
})
请参阅:http://getbootstrap.com/javascript/#modals-events
其次,我更喜欢使用jQuery创建DOM元素,比如
$("<div>").addClass("col-md-4").attr("data-target","#myModal").append(
$("<div>").addClass("modal fade")//add more here
);