在使用 replaceWith() 后无法在 jQuery 中设置 CSS 和单击处理程序

unable to set CSS and click handler in jQuery after use of replaceWith()

本文关键字:设置 CSS 程序 处理 单击 jQuery replaceWith      更新时间:2023-09-26

我正在使用jQuery将普通复选框替换为图像。我能够用图像替换复选框,但无法在图像上设置 CSS 和单击处理程序。

这是我的jQuery代码。

(function ($) {
    $.fn.SetOnOff = function (onImage,offImage) {
         debugger;
         var html = '<img style="width: 80px; height: 30px" src="'+offImage +'"/>';
                $(this).replaceWith(html);
         $(html).css('cursor','pointer');
          $(html).click(function(){
             var fileName = $(this).attr('src');
                if (fileName == onImage)
                    $(this).attr('src', offImage);
                else
                    $(this).attr('src', onImage);
         });
        return  $(this);
    };
} (jQuery));

任何人都可以告诉我该怎么做吗?

使用此链接进行测试

对动态创建的元素使用事件委托

$("button").click(function () {
    var v = "<div>" + $(this).text() + "</div>";
    $(this).replaceWith(v);
    $(v).css('cursor', 'pointer');
});
$(document).on("click", "div", function () {
    alert($(this).text());
});

演示

您的cssclick方法不是在替换的元素上调用的,而是在从html字符串生成的新创建的HTML jQuery上调用的。

试试这个:

 var $v = $("<div>" + $(this).text() + "</div>");
 $(this).replaceWith($v);
 $v.css('cursor', 'pointer');
 $v.click(function () {
     alert('a');
 });

您正在尝试将 CSS 设置为字符串。 让它成为jQuery对象,如下所示

(function ($) {
$.fn.SetOnOff = function (onImage,offImage) {
     debugger;
     var html = $('<img style="width: 80px; height: 30px" src="'+offImage +'"/>');
            $(this).replaceWith(html);
     $(html).css('cursor','pointer');
      $(html).click(function(){
         var fileName = $(this).attr('src');
            if (fileName == onImage)
                $(this).attr('src', offImage);
            else
                $(this).attr('src', onImage);
     });
    return  $(this);
};
} (jQuery));

演示