[英]Append html to bootstrap modal not working
I'm trying to load an image from a php foreach loop into a bootstrap modal using data- attribute but nothing showing in target div - here's my code: 我正在尝试使用data-属性将图像从php foreach循环加载到引导模态,但目标div中没有任何显示-这是我的代码:
<script>
$(document).ready(function(){
$( ".subscribe" ).on( "click", function() {
var imgURL = $( this ).attr( "data-img-url" );
console.log(imgURL);
});
$( "#subscribeModal" ).on('shown', function(){
$('#sub_img').append('<img src="'+imgURL+'" />');
});
});
</script>
You have 2 issues. 您有2期。 First is the
imgURL
parameter mentioned elsewhere. 首先是其他地方提到的
imgURL
参数。 Second, the name of the event to bind to should be shown.bs.modal
. 其次,应该显示要绑定的事件的名称
shown.bs.modal
。 The documentation on the Bootstrap website says: Bootstrap网站上的文档说:
show.bs.modal This event fires immediately when the show instance method is called.
show.bs.modal调用show实例方法时,将立即触发此事件。 If caused by a click, the clicked element is available as the relatedTarget property of the event.
如果是由单击引起的,则clicked元素可用作事件的relatedTarget属性。
$( "#subscribeModal" ).on('shown.bs.modal', function(){
$('#sub_img').append('<img src="'+imgURL+'" />');
});
});
The variable imgURL
is local to the click handler, so it won't be accessible inside the shown
handler. 变量
imgURL
在点击处理程序中是本地变量,因此在shown
处理程序中无法访问。 Declare the variable in a shared scope of both those functions to make it work 在这两个函数的共享作用域中声明变量以使其起作用
$(document).ready(function () {
var imgURL;
$(".subscribe").on("click", function () {
imgURL = $(this).attr("data-img-url");
console.log(imgURL);
});
$("#subscribeModal").on('shown', function () {
$('#sub_img').append('<img src="' + imgURL + '" />');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.