MVC - jQuery 无法访问由 Ajax 和 jQuery 创建的附加局部视图

MVC - jQuery could not access to appended partial view which created by Ajax and jQuery

我有一个简单的部分视图,它由 Ajax 调用,并将由 jQuery 添加到 cshtml 页面上的跨度。到现在为止,一切都很完美。

Create.cshtml

<span id="SpanCoverPhoto"></span>

myjQuery.js

$(document).ready(function () {

    $('select[id=BusinessList]').before(function () {
        loadCoverPhotos($('select[id=BusinessList]'));
    });

    $('select[id=BusinessList]').change(function () {
        loadCoverPhotos($('select[id=BusinessList]'));
    });

    function loadCoverPhotos(businessList) {

        var id = businessList.val();

        $.ajax({
            url: "/CoverPhotos/Load",
            type: "POST",
            data: { 'BId': id },
            success: function (data) {
                $('span[id=SpanCoverPhoto]').html(data);
            },
            error: function () {
                alert("Cover photos not loaded");
            }
        });
    }

});

局部视图:

@model IEnumerable<banaam.Models.CoverPhoto>

<div>
   @foreach (var item in Model)
    {
      <div class="Coverphoto">
         <img src="~/Images/BusinessBackground/Thumb_@item.Wallpaper" class="img-thumbnail" style="max-width:120px; max-height:100px;" />
      </div>
    }
</div>

现在,我想点击一张照片,然后再次按jQuery处理。但是,将数据附加到 "view page source" 处未显示的跨度,我使用 F12 时只能看到它们。

你能告诉我吗,我怎样才能点击照片并得到 jQuery 的回复?

致以诚挚的问候,非常感谢您的宝贵时间,

阿敏

您可以使用 jQuery On 将事件绑定到初始页面加载后加载的项目。

$(document).on('.Coverphoto').click(function(){ //your implementation here });

注意:您无法看到使用“查看页面源代码”加载的文档内容。它们仅在使用 F12(开发者工具)时可见

您需要在 document 和 jQuery 上设置一个侦听器,以便在整个页面上侦听此事件。即使添加了新元素。

你可以这样做:

$(document).on('click', '.your-class', function(event) {
    console.log('Image clicked!');
});

将 .your-class 更改为 .img-thumbnail for ex.
并查看文档:http://api.jquery.com/on/.