javascript - 为什么 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暂时显示,按钮消失的原因是什么,按钮消失了怎么办?
解决方案
将新容器添加到.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/
推荐阅读
- javascript - 匹配字符串中的单词,无论中间有什么
- c# - Azure.DocumentDb HTTP 请求中找到的 MAC 签名与计算的签名不同
- java - OSNotificationPayload 无法转换为 JSONObject
- sql - 从 2 个表中选择有条件绑定的列到一行
- nativescript - iOS 中使用 nativescript-google-maps-sdk 的地图中心错误
- google-cloud-dataflow - 停止管道并启动新管道后,Beam/Dataflow 可以保持状态吗?
- python - 字母汤 - 他们给我方向网格,我必须返回那个方向的整个字母(Python)
- elasticsearch - 具有多个字段的弹性搜索基数聚合
- php - 当我想显示我的结果时,如何在 PDO PHP 中使用 UTF8?
- python-3.x - 如何转换这个数组类型,我想成为 float64 类型