我在 html 页面上有两个 div。这基本上只是 html 布局上的两列。我在左列 (div) 中有一个按钮列表。我用 OK 和 REMOVE 字形标记了每个按钮。现在我希望当我单击按钮的删除图标时它应该删除它否则如果我单击按钮的确定图标然后它应该将它移动到右列 (div)。我在这里创建了一个 js fiddle :JS Fiddle
HTML:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="row">
<div class="col-sm-4" style="background-color:lavender;border: solid 1px blue;">
<div class="text-center">
<div class="list">
</div>
</div>
</div>
<div class="col-sm-8" style="background-color:lavenderblush;border: solid 1px blue;">
<div class="accepted">
</div>
</div>
</div>
JavaScript:
var load = function () {
$.getJSON('https://api.myjson.com/bins/4skih', function (res) {
$.each(res.data, function (key, val) {
addTag(val.tag, key);
});
});
};
var init = function () {
load();
$('.list').on('click', 'button', function () {
$(this).parent().acceptTag(this);
$(this).parent().remove();
});
};
$(document).ready(init);
// Add tag to html.
var addTag = function (tag) {
$("<div><button class='tag'>" + tag + "</button><span class='glyphicon glyphicon-ok' aria-hidden='true''></span><span class='glyphicon glyphicon-ok' aria-hidden='true''></span></div>").appendTo('.list');
};
var acceptTag = function (tag) {
$("<div><button class='tag'>" + tag + "</button><span class='glyphicon glyphicon-ok' aria-hidden='true''></span><span class='glyphicon glyphicon-ok' aria-hidden='true''></span></div>").appendTo('.accepted');
};
任何帮助将不胜感激。
最佳答案
我确实对您的代码做了细微的改动以使其正常工作。
你很接近!
解释:
您对 acceptTag
函数的调用不正确,在 .list
事件委托(delegate)中点击 button
。
我简单地调用了它,就像您在 load()
函数中使用 addTag
函数所做的那样。
我简化了这个 acceptTag
函数,因为很明显,您想将父对象(包装 div
)发送给它。
所以所有的 button
定义都已经存在了。它由 tag.html()
检索,这是按钮的父 HTML 内容。您只需将它重新包装在 div
中即可。
查看我的 Fiddle
var load = function () {
$.getJSON('https://api.myjson.com/bins/4skih', function (res) {
$.each(res.data, function (key, val) {
addTag(val.tag, key);
});
});
};
var init = function () {
load();
$('.list').on('click', 'button', function () {
acceptTag( $(this).parent() ); // Changes here
$(this).parent().remove();
});
};
$(document).ready(init);
// Add tag to html.
var addTag = function (tag) {
$("<div><button class='tag'>" + tag + "</button><span class='glyphicon glyphicon-ok' aria-hidden='true''></span><span class='glyphicon glyphicon-ok' aria-hidden='true''></span></div>").appendTo('.list');
};
var acceptTag = function (tag) { // Changes here
$('.accepted').append( "<div>" +tag.html()+ "</div>" );
};
关于jquery - 如何使用 JQuery 将元素/按钮从一个 div 移动到另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277061/