Javascript导致DOM元素被删除

时间:2013-04-26 06:04:30

标签: javascript html css

这可能只是我盯着代码太长时间并且遗漏了一些重要内容的另一个例子。基本上,我有一个脚本,当一个.click(jQuery)事件发生时,在WebKit中,用另一个项目的内容填充另一个脚本。但是,由于某种原因,在项目上单击多次会导致删除DOM元素。有任何想法吗? JSFiddle代码示例链接如下。

这是我认为是罪魁祸首的功能:

$(".vote-divs .vote-div").click(function () {
        $(".vote-none").hide()
        $(".step-2-column-left .vote-div").each(function () {
            $(this).hide();
        });
        $("#" + $(this).attr("id") + "-s").show();

        $(".confirm-s").each(function () {
            $(this).hide();
        });

        if ($(this).attr("id") == "vote-grow") {
            $("#donation-vote-for").val("Grow");
            $("#confirm-grow-s").show();
        } else if ($(this).attr("id") == "vote-stache") {
            $("#donation-vote-for").val("Stache");
            $("#confirm-stache-s").show();
        } else if ($(this).attr("id") == "vote-shave") {
            $("#donation-vote-for").val("Shave");
            $("#confirm-shave-s").show();
        } else if ($(this).attr("id") == "vote-mutton") {
            $("#donation-vote-for").val("Mutton");
            $("#confirm-mutton-s").show();
        } else if ($(this).attr("id") == "vote-manchu") {
            $("#donation-vote-for").val("Manchu");
            $("#confirm-manchu-s").show();
        }


        console.log(event.target);
        $(".vote-none").html(event.target);

        goTo("3");
    });

JSFiddle

2 个答案:

答案 0 :(得分:0)

尝试

$(".vote-none").html($(event.target).clone());

而不是

$(".vote-none").html(event.target);

演示:Fiddle

答案 1 :(得分:0)

.html()需要一个字符串。您提供了一个节点。当你这样做时,jQuery接受这个节点并将它附加到另一个元素。如果你真的想用另一个元素的内容填充元素,那么解决方案是

$(".vote-none").html(event.target.innerHTML);

$(".vote-none").html($(this).html());

请注意,在您的情况下this等于event.target

相关问题