【发布时间】:2017-02-20 21:33:40
【问题描述】:
我遇到了$('element').remove(); 不起作用的问题。
我已经阅读了许多其他存在语法问题并且单击未正确注册在按钮上的答案。
我遇到了不同的问题。点击是有效的,但唯一删除的是 newRowDiv。
开头是<newRowDiv><child><child><child></newRowDiv>
最后
<child><child><child>
newRowDiv 不见了,但孩子们就留在那里。
奇怪的是代码工作正常,直到我添加trigger('create')
这是关于我的代码的作用
buildRows = function(){
//Adds the new div to the placement div
var placementDiv = $('#placementDiv');
placementDiv.append("<div class='newRowDiv'></div>");
//Adds the child elements to the new div
var newRowDiv = $(".newRowDiv:last");
newRowDiv.append("<label>Title</label>");
newRowDiv.append("<input>");
newRowDiv.append("<a id='plusButton'>Plus</a>");
//Adds the click event to the new plus button (Works fine)
newRowDiv.find('#plusButton').click(function (event) {
var button = $(event.target);
//Adds the delete button (Works fine)
var newRowDiv = button.parent('.newRowDiv');
newRowDiv.append('<a id="deleteButton">Delete</a>');
//Adds the click event to the button (Works fine)
newRowDiv.find('#deleteButton').click(function (event) {
//Removes the parent newRowDiv and all child elements (Doesn't work)
var button = $(event.target);
button.closest('.newRowDiv').remove();
});
//Removes the plus button (Works fine)
button.remove();
//Adds the new rows section (Works fine)
buildRows();
//Without this the new elements don't display correctly
//With this the remove only removes the element and leaves it's children behind
placementDiv.trigger('create');
});
}
buildRows()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="placementDiv">
</div>
编辑: 代码 sn-p 正在运行。我只是在运行 trigger.('create') 时遇到问题,它正在添加一些 jquery 移动格式
编辑 2:它似乎与 jquery mobile 的弹出格式有关。因为它在没有弹出窗口的代码 sn-p 中运行良好,并且在我添加 trigger('create') 之前它在我的原始代码中运行良好
【问题讨论】:
-
这个函数会被多次使用来添加行吗?如果是这样,那么您将添加多个具有相同 ID 的按钮。那是无效的 HTML。 ID 必须是唯一的。很有可能它会导致您的点击事件不触发,因为您尝试在其上定义它们的元素无效。把它整理出来,然后看看你是否还有问题。而且您的 sn-p 无法编译-您是否从最后缺少一些括号?
-
如果您在另一个
bind中使用bind,您的事件只会在您单击父绑定上的初始点击后被绑定。将第二个click()移到外面,与第一个在同一层,它将开始工作。 -
@Andrei 绑定工作正常。我使用 chrome 中的 javascript 调试器进行了验证。并且点击事件被捕获
-
@darthNater 如果你这么说,你可能知道得更好。毕竟,这是你的剧本。保重。
-
@AndreiGheorghiu 我无法弄清楚为什么它不能与触发器('create')一起使用,所以我添加了 data-role='none' 并手动添加了触发器(“创建”)添加。它现在按预期工作。感谢您的帮助
标签: jquery html jquery-mobile