我正在从 JSON feed 生成条目列表。我想单击一个 div 并调出编辑模式。我在从 click
事件获取 relatedTarget 时遇到一些问题。它返回为未定义。
还有其他方法将数据传递到模式吗?
$.getJSON('api/v1/module', function(data){
$.each(data, function(i, learning) {
var $div = $('<div>')
.append(
$('<p>').text(learning.title),
$('<p>').text(learning.lastupdated)
)
.addClass('panel panel-default')
.attr('data-title', learning.title)
.appendTo('.module-list')
.on('click', function(){
$('#edit-module').modal({
show: true
})
})
});
})
$('#edit-module').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('title') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-body input').val(recipient)
console.log( event.relatedTarget )
console.log( event )
console.log( button )
console.log( JSON.stringify(button) )
})
最佳答案
来自Boostrap docs :
If caused by a click, the clicked element is available as the relatedTarget property of the event.
但是这里的显示是由modal()
引起的,而不是初始点击。
要按照文档中的描述让点击触发显示,您需要使用 Boostrap 的 data-toggle
调用模式。添加这些数据属性,并删除您的 .on()
处理程序:
$.getJSON('api/v1/module', function(data){
$.each(data, function(i, learning) {
var $div = $('<div>')
...
.attr('data-title', learning.title)
.attr("data-toggle", "modal")
.attr("data-target", "#edit-module")
.appendTo('.module-list')
});
})
关于javascript - 单击 div 时显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41527261/