javascript - 为什么 jQuery .html ("abc") 只临时插入?

标签 javascript jquery

我有一个调用函数的 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”中,该框会按预期连续显示,但按钮消失了。

在各自的情况下,连续显示框和临时显示框时按钮消失的原因是什么?按钮消失该怎么办?

最佳答案

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

下面的代码实现了我所理解的期望结果;新的 div 出现在按钮后面。新<div>附加到现有的<div> ,在按钮后使用 $("button").parent()选择现有的<div> 。追加新的<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>

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

关于javascript - 为什么 jQuery .html ("abc") 只临时插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54263135/

相关文章:

javascript - 放大镜不放大 CSS/JS

javascript - 使用 jQuery 拖放从 SQL 表中删除一行

javascript - 从不同的js文件访问变量

javascript - 随机化所有字符串字符的大写/小写

javascript - 一段 jquery 代码在 Angular 指令中不起作用

jquery - 使用 Jquery Jcarousel,我需要帮助修改分页

jquery - jquery 中的 .load() 和 .fadeIn

javascript - 将 jquery-ui 事件绑定(bind)到主干事件

javascript - Javascript 图像交换上的 CSS 过渡

javascript - window.location.hostname 不带 .com 或任何其他前缀