Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么jQuery';html(“abc”)是否仅临时插入?_Javascript_Jquery - Fatal编程技术网

Javascript 为什么jQuery';html(“abc”)是否仅临时插入?

Javascript 为什么jQuery';html(“abc”)是否仅临时插入?,javascript,jquery,Javascript,Jquery,我有一个调用函数的html按钮,但是当按钮单击时,插入的div只出现一秒钟,然后消失,无论是在视觉上还是在html树中 function openBox () { $( '#0' ).click( function () { var container = $( "<div>" ).css({ height : "200px", width : "200px", position : "absolute",

我有一个调用函数的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 );
});
}
函数openBox(){
$('#0')。单击(函数(){
变量容器=
$(“”).css({
高度:“200px”,
宽度:“200px”,
位置:“绝对”,
“背景色”:“黑色”,
});
$('button.box').html(容器);
});
}
如果我将JS中创建的div插入到“button.box”中,它只会在瞬间临时显示。html如下所示:

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

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


按钮在框的连续显示和框在各自情况下的临时显示中消失的原因是什么?如何处理按钮消失?

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

下面的代码实现了我所理解的期望结果;按钮后出现的新div。新的
通过使用
$(“按钮”).parent()
选择现有的
添加到按钮后的现有
。将新的
附加到按钮本身
$(“按钮”).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>

$(文档).ready(函数(){
$('#0')。单击(函数(){
变量容器=$(“”)。css({
高度:“200px”,
宽度:“200px”,
位置:“绝对”,
“背景色”:“黑色”,
});
$(this.parent().append(容器);
});
});

有关jQuery
append
方法和其他方法的更多信息,请参见其文档:

如果您的
位于
中,则它可能正在提交它。将
type=button
添加到
HTML以防止出现这种情况。默认按钮类型为“提交”。由于您添加的是绝对定位的HTML,猜测
按钮.box
没有相对定位,因此它会消失。当您在支架上使用
html
时,它会替换支架内的所有内容,因此您需要添加。@尖头按钮类型是问题所在,无法更新您的答案