2016-01-24 46 views
0

我在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">&times;</button>' + 
     '<div class = "modal-footer"></div></div></div></div></div>')); 

這是醜陋的,容易出錯的,難以維護,難以閱讀。它能以更優雅的方式完成嗎?

回答

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 
    ); 
    
+0

這似乎使事情變得更加優雅,更易於閱讀。謝謝。 – user3804799