Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用replaceWith()后,无法在jQuery中设置CSS和单击处理程序_Javascript_Jquery - Fatal编程技术网

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

Javascript 使用replaceWith()后,无法在jQuery中设置CSS和单击处理程序,javascript,jquery,Javascript,Jquery,我使用jQuery将普通复选框替换为图像。我可以用图像替换复选框,但无法设置CSS并单击图像上的处理程序 这是我的jQuery代码 (函数($){ $.fn.SetOnOff=函数(onImage,offImage){ 调试器; var html=''; $(this).replacetwith(html); $(html.css('cursor','pointer'); $(html)。单击(函数(){ var fileName=$(this.attr('src'); 如果(文件名==onI

我使用jQuery将普通复选框替换为图像。我可以用图像替换复选框,但无法设置CSS并单击图像上的处理程序

这是我的jQuery代码

(函数($){
$.fn.SetOnOff=函数(onImage,offImage){
调试器;
var html='';
$(this).replacetwith(html);
$(html.css('cursor','pointer');
$(html)。单击(函数(){
var fileName=$(this.attr('src');
如果(文件名==onImage)
$(this.attr('src',offImage);
其他的
$(this.attr('src',onImage);
});
返回美元(此);
};

}(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));
(函数($){
$.fn.SetOnOff=函数(onImage,offImage){
调试器;
var html=$('');
$(this).replacetwith(html);
$(html.css('cursor','pointer');
$(html)。单击(函数(){
var fileName=$(this.attr('src');
如果(文件名==onImage)
$(this.attr('src',offImage);
其他的
$(this.attr('src',onImage);
});
返回美元(此);
};
}(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());
});
$(“按钮”)。单击(函数(){
var v=“”+$(this.text()+”;
$(此)。替换为(v);
$(v).css('cursor','pointer');
});
$(文档)。在(“单击”,“div”,函数(){
警报($(this.text());
});

您的
css
click
方法不会在替换的元素上调用,而是在新创建的HTML上调用,jQuery将从您的
HTML
字符串生成

请尝试以下方法:

 var $v = $("<div>" + $(this).text() + "</div>");
 $(this).replaceWith($v);
 $v.css('cursor', 'pointer');
 $v.click(function () {
     alert('a');
 });
var$v=$(“”+$(this.text()+“”);
美元(本)。替换为($v);
$v.css(‘光标’、‘指针’);
$v.click(函数(){
警报(“a”);
});

我发现这个代码适合我。谢谢haim770