javascript - jQuery - 使用 remove() 后点击功能不工作

标签 javascript jquery

HTML 示例:

<div class="row" id="ThumbnailHolder">
    <div class="col-md-12">
        <img src="http://images.sportsdirect.com/images/products/16503236_pit.jpg" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/16503236_l.jpg">
        <img src="http://images.sportsdirect.com/images/products/16503236_piat_a1.jpg" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/16503236_l_a1.jpg">
    </div>
</div>

这是我的代码:

$(document).ready(function() {
    $('.Thumbnails').each(function() {
        $(this).click(function() {
                  var BigImageLink = $( this ).attr( "bigimagelink" );
                  $('#ImgBigLink').attr('href', BigImageLink);
                  $('#productImgDefault').attr('src', BigImageLink);
        });

    });     
});

这个功能很好用。当我单击具有 Thumbnails 类的元素时,一切都按照我的需要进行。当我执行以下代码部分时,问题就来了:

$.ajax({
    url: 'CheckColorPrice.php',
    type: 'POST',
    data: {
        url: '<?php echo $url;?>',
        ColorId: ColorNumber,
        ProductUrl: '<?PHP echo $ProductUrlWithoutCode;?>'
    },
    dataType: 'json',
    success: function (data) {
            $( ".Thumbnails" ).remove();
            $.each(data.thumbnails, function(index, thumbnails) {                             
            $('#ThumbnailHolder div').append('<img src="http://images.sportsdirect.com/images/products/' + thumbnails + '" class="Thumbnails" bigimagelink="http://images.sportsdirect.com/images/products/' + thumbnails + '">');  
            }); 
    }
});

我很确定问题出在 $( ".Thumbnails").remove(); 但我需要它来删除所有类 Thumbnails 和然后用附加有相同结构和类的新的替换它们。执行此代码时,Thumbnails 上的CLICK 功能没有响应。没有任何输出错误。为什么我的 click 功能不再起作用?

我很确定你能帮我解决这个问题。

提前致谢!

最佳答案

目前您使用的称为“直接”绑定(bind),它只会附加到您的代码进行事件绑定(bind)调用时页面上存在的元素。

您需要使用 Event Delegation使用 .on()委托(delegate)事件方法,当动态生成元素时。

一般语法

$(staticParentElement).on('event','selector',callback_function)

示例

$('#ThumbnailHolder div').on('click', '.Thumbnails', function(){    
    var BigImageLink = $( this ).attr( "bigimagelink" );
    $('#ImgBigLink').attr('href', BigImageLink);
    $('#productImgDefault').attr('src', BigImageLink);
});

关于javascript - jQuery - 使用 remove() 后点击功能不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37500220/

相关文章:

javascript - 需要帮助了解如何从 JS 文件格式化表数据的内联 CSS

javascript - 检查字符串的某个部分是否包含子字符串

javascript - 如何为按键设置动画?

javascript - 在 div d3.js 中显示选择选项

javascript - React Redux - 无法使用将组件的方法传递给子组件 - 未定义错误

javascript - 导出图表抛出 RangeError : Maximum Call Stack Size Exceeded in highcharts-more. js

javascript - native JavaScript - 检测何时单击 div 远离/未聚焦

http - jQuery Ajax : redirect to other pages without wait the result

jQuery 一次 onClick 加载脚本

javascript - 使用 Javascript 从远程端点将 html 内容附加到 div 中