如何克隆< script> jQuery标签 [英] How to clone <script> tags with jQuery
问题描述
我有以下代码(简化后可以看到其背后的逻辑):
I have the following code (simplified to see the logic behind):
<div id="alfa">Text
<script>
$("#alfa").click(function() {
alert($(this).attr("id"));
});
</script>
</div>
<script>
var clone = $("#alfa").clone().attr("id",$("#alfa").attr("id")+"_1");
$("#alfa").after(clone);
</script>
当我单击克隆的文本时,我需要看到"alfa_1",但是什么也没发生.
I need to see "alfa_1" when I click in the cloned Text, but nothing happens.
当我使用可以正常工作的clone(true,true)时,但在Firebug中看不到克隆的div的代码,无法了解实际发生的情况.
When I use clone(true,true) that works, but I don't see the code of the cloned div in Firebug to see what really happens.
我也不知道为什么单击原始div两次会触发警报.
Also I don't know why clicking the original div the alert is triggered twice.
谢谢.
推荐答案
当我单击克隆的文本时,我需要看到"alfa_1",但是什么也没发生.
I need to see "alfa_1" when I click in the cloned Text, but nothing happens.
在<script>
元素上执行DOM或innerHTML操作在浏览器中是不一致的,并且就JavaScript执行周期而言实际上没有任何意义.在所有情况下都避免使用它.
Doing DOM or innerHTML manipulations on <script>
elements is inconsistent in browsers and doesn't really make any sense in terms of the JavaScript execution cycle. Avoid it in all cases.
如果要复制DOM元素及其jQuery事件处理程序,请使用clone(true)
:
If you want to copy DOM elements together with their jQuery event handlers, use clone(true)
:
<div id="alfa">Text</div>
<script type="text/javascript">
$('#alfa').click(function() {
alert(this.id);
});
var clone= $('#alfa').clone(true);
clone[0].id+= '_1'; // sorry, I couldn't bring myself to do this the jQuery way
$('#alfa').after(clone);
</script>
这篇关于如何克隆< script> jQuery标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!