首页 > 解决方案 > 为什么 jQuery 的 .html("abc") 只是临时插入?

问题描述

我有一个调用函数的 html 按钮,但是当单击按钮时,插入的 div 只出现一秒钟然后消失,无论是在视觉上还是在 html 树中。

function openBox () {

$( '#0' ).click( function () {

    var container = 
    $( "<div>" ).css({
        height : "200px",
        width : "200px",
        position : "absolute",
        "background-color" : "black",
    });

     $( 'button.box' ).html( container );
});
}

如果我将在 JS 中创建的 div 插入到“button.box”中,它只会暂时显示一瞬间。html看起来像这样:

<div class="holder">
  <button id="0" class="box fa fa-paint-brush"></button>
</div>

但是,如果插入到具有相同 html 结构的“div.holder”中,则该框会按预期连续显示,但按钮消失了。

在各自的情况下,box不断显示和box暂时显示,按钮消失的原因是什么,按钮消失了怎么办?

标签: javascriptjquery

解决方案


将新容器添加到.holder类时,按钮会消失,因为该.html()方法正在替换所选元素中的内容。为了添加框并保留按钮,.append()是合适的jQuery方法。

下面的代码实现了我理解的预期结果;新的 div 出现在按钮之后。新<div>的被附加到现有的<div>,在按钮之后通过使用$("button").parent()来选择现有的<div>。将 new 附加<div>到按钮本身$("button").append()会将 div 添加到按钮内部。

<div class="holder">
    <button id="0" class="box fa fa-paint-brush" type="button"></button>
</div>

<script>
 $(document).ready(function(){
    $('#0').click( function () {
        var container = $( "<div>" ).css({
            height : "200px",
            width : "200px",
            position : "absolute",
            "background-color" : "black",
        });
        $(this).parent().append( container );
    });
});
</script>

有关 jQueryappend方法和其他方法的更多信息,可以在他们的文档中找到:http: //api.jquery.com/append/


推荐阅读