javascript - 单击 div 时显示表单

标签 javascript jquery twitter-bootstrap bootstrap-modal

我正在从 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/

相关文章:

Javascript IE8 未从 AttachEvent 获取 'this'

javascript - 键值对列表到数组数组

html - Bootstrap : How to get a column with 100% the height of another column

html - 我怎么能把新 block 放在另一个 block 之上

javascript - Bootstrap Collapse 不会自动折叠

javascript - 避免错误 <yourObject> 未在 Ember.js 中定义

javascript - 检测 Javascript 中字体平滑设置的变化

javascript - 如何使用外部容器为 iframe 设置全屏?

javascript - 如何将文本从 DIV 数组添加到 DIV

javascript - Bootstrap - $(...).modal 不是函数/解决方案 : DataTables conflict (multiple includes of jquery)