2017-09-15 47 views
0

我曾猜测这段代码可以工作。但JS没有提醒任何事情。 在替换内容上运行功能的最佳方式是什么?这是一个简单的代码,你可以看到,如果你使用jQuery。只有你有建议,我才需要答案。用jquery替换内容运行函数

<script src="https://code.jquery.com/jquery-1.10.2.js"></script> 

<button type="button" id="add" name="sub">Add</button> 

<script> 
$(document).on('click',"#add",function(){ 
$(this).replaceWith("<button type='button' id='sub'> Alert </button>"); 
}); 

$(document).ready(function(){ 
$("#sub").click(function() 
{ 
alert("Does it alert?"); 
}); 
}); 
</script> 
+0

可能的复制https://stackoverflow.com/questions/770308/events-not-registering -after-replace- – Niladri

+0

你r最后的代码部分应该按照第一个脚本部分中的选择格式 – MaxZoom

回答

0

添加经由

$(document).on('click', '#sub', function() { }) 

$(document).on('click',"#add", function() { 
 
    $(this).replaceWith("<button type='button' id='sub'> Alert </button>"); 
 
}); 
 

 
$(document).ready(function() { 
 
    $(document).on('click', '#sub', function() { 
 
     alert("Does it alert?"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button type="button" id="add" name="sub">Add</button>