How to clone <script> tags with jQuery

ぐ巨炮叔叔 提交于 2019-12-12 01:14:08

问题


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>

I need to see "alfa_1" when I click in the cloned Text, but nothing happens.

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.

Also I don't know why clicking the original div the alert is triggered twice.

Thanks.


回答1:


I need to see "alfa_1" when I click in the cloned Text, but nothing happens.

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.

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>



回答2:


The alert for the original div is triggered twice because the script is defined inside the div. Move the script out of the div and it should work as expected:

<div id="alfa">Text</div>
<script>
    $("#alfa").click(function() {
        alert($(this).attr("id"));
    });
</script>


来源:https://stackoverflow.com/questions/7534476/how-to-clone-script-tags-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!