在 JSFiddles 中测试 Bootstrap 表时,我想做的是当我单击表内的按钮时,该按钮会消失并被普通文本取代。以下是标记的相关部分:
<tbody>
<tr>
<td>John Doe</td>
<td>my@gmail.com</td>
<td><button class="disabled" data-bind="click: dosomething.bind($data, 'was', 'sup')" type="button" class="btn btn-warning">Crear Cuenta</button></td>
</tr>
</tbody>
因此使用 KnockoutJS 将事件绑定(bind)到单击按钮时,我执行了以下操作:
function ViewModel() {
var self = this;
self.dosomething = function (data, event, param1, param2) {
var $stuff = $(param2.target).prop("disabled",true);
var $stuff2 = $(param2.target).hasClass("disabled");
var $stuff3 = $(param2.target).parent();
$(param2.target).parent().empty();
$(param2.target).parent().html("hello");
}
self.donext = function(){
var $stuff = $(".disabled").prop("disabled",false);
}
}
var app = new ViewModel();
ko.applyBindings(app);
但是,hello
根本不会呈现。但是当我删除 $(param2.target).parent().empty();
行时,该按钮将被替换为 hello
,正如我最初想要的那样。如果 .empty()
只删除子内容,为什么我不能在之后添加 html 内容?
最佳答案
声明
$(param2.target).parent().empty();
清空父元素的所有内容。如果您清空某个其他(子)元素的父元素中的所有内容,您认为子元素会发生什么情况?对:它不见了。因此,随后设置 .html()
内容的尝试将不起作用,因为父级不再是父级。
您可以使用来自父元素的链接:
$(param2.target).parent().empty().html("hello");
之所以可行,是因为对 .empty()
的调用返回了包装父对象的 jQuery 对象。在您的代码中不起作用的是从(不再)子元素重新开始。
关于javascript - 为什么在使用 .empty() 后无法将 Html 插入 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47463340/