下面是我的小提琴,展示到目前为止我的代码:http://jsfiddle.net/abhighosh18/dp240twL/1/
问题描述:
我在这里使用event-delegation,在单击div时,我将单击的div放入对象中,并给用户一个选项,将标题赋予该div,然后将文本附加到div或完全删除组件。
我就是这样使用事件委托的:
var obj1, obj2;
$(document).on('click', ".comp1", function () {
obj1 = $(this);
console.log('Square clicked');
$(".componentTitle").show();
$(".btnSaveTitle").show();
$(".btnRemove").show();
});
$(document).on('click', ".comp2", function () {
obj2 = $(this);
console.log('Circle clicked');
$(".componentTitle").show();
$(".btnSaveTitle").show();
$(".btnRemove").show();
});现在问题是,这里有两个形状:正方形和圆形。现在,事件正确地触发圆圈-文本附加成功。现在,当我点击正方形并为它保存标题时,文本只会附加到圆圈中。
以下是我如何将文本附加到组件中:
$(".btnSaveTitle").click(function () {
var title1 = $(".componentTitle").val();
if (obj1 !== undefined) {
obj1.find(".label1 center").html(title1);
obj1.attr("title", title1);
}
if (obj2 !== undefined) {
obj2.append("<center>" + title1 + "</center>");
obj2.attr("title", title1);
}
$(".btnRemove").hide();
$(".componentTitle").hide();
$(".btnSaveTitle").hide();
});为什么事件没有被委派,或者为什么文本没有被附加到正方形组件?
注意:,我通过$.POST保存整个事件计划的样式,并将属性输入到DB。
发布于 2015-05-06 06:49:49
附加到椭圆的代码是:
if (obj2 !== undefined) {
obj2.append("<center>" + title1 + "</center>");
obj2.attr("title", title1);
}但是,附加到矩形的代码是:
if (obj1 !== undefined) {
obj1.find(".label1 center").html(title1);
obj1.attr("title", title1);
}如果将obj1.find()调用更改为椭圆代码的obj2.append()调用,则它具有相同的功能。
为了避免在更改标题时将文本附加到每个元素,可以在empty()之前对其进行append()。
obj2.children('center').remove();
obj2.append("<center>" + title1 + "</center>");若要在单击“保存”按钮后清除文本框,只需在事件处理程序中为单击按钮添加对val()的调用,
$(".btnSaveTitle").click(function () {
var title1 = $(".componentTitle").val();
$(".componentTitle").val("");更新小提琴:http://jsfiddle.net/dp240twL/4/
发布于 2015-05-06 07:05:29
您需要做的一件事是,当您存储obj1时
obj1 = $(this);
obj2 = undefined;和
obj2 = $(this);
obj1 = undefined;因为,附加的代码取决于“未定义”的对象。
https://stackoverflow.com/questions/30059915
复制相似问题