2011-02-23 68 views
0

我面临着非常奇怪和困难的问题。我正在开发一个Web应用程序,我创建了一些小部件。如果我点击图标,小部件编辑器将出现在模块弹出窗口中,用户可以输入他的数据,并且数据将作为标签显示在仪表板上。我在放置在仪表板上的标签上方有一个“编辑”按钮,现在我想添加删除按钮,假设用户将在仪表板上添加小部件,然后他发现他不需要该仪表板,因此他点击了删除按钮应该被删除,如果用户在删除之后再次想要该小部件,当他点击之前删除的特定小部件的图标时,该小部件应该再次出现。我试图做到这一点,但一旦我点击删除按钮,我可以删除小部件,但当我点击小部件的图标时,我无法取回。jquery .click问题

请帮我解决这个问题

+3

有很少或几乎没有机会任何人都可以帮助你没有看到你的代码就可以工作。创建一个简化示例,以便复制问题所需的最低限度,并将其发布到问题的文本中,并且*可选地将其发布到像http://jsbin.com或http://jsfiddle.net这样的站点。 (但不是*只是*到一个外部网站。) – 2011-02-23 12:01:06

+1

那么这不是很真实,公平点,但不是真实的:)当他需要使用'.live时,我认为他/她使用'.click'或''bind' '或'.delegate',以便它记住相同/相似元素的未来元素:)这就是说我也可能是错误的:) – Val 2011-02-23 12:16:44

+0

如何删除小部件?通过“删除”或“隐藏”? – 2011-02-23 12:36:51

回答

2

只是走一个猜测你希望做什么,这里是添加一个div,你可以再次关闭的例子:

设置:

var WIDGET_MARKUP = 
    "<div class='widget'>I'm the widget. " + 
    "<span class='close'>Close</span>" + 
    "</div>"; 

// Opens the widget, returns true; if the widget is already 
// open, doesn't open a a second and returns false. 
function openWidget(onClose) { 
    var widget; 

    // If there's already one open, don't do anything 
    if ($("div.widget").length > 0) { 
    // Already open, don't open another 
    return false; 
    } 

    // There isn't, add one 
    widget = $(WIDGET_MARKUP); 
    widget.appendTo(document.body); 
    widget.delegate('span.close', 'click', function() { 
    // Remove the widget 
    widget.remove(); 

    // Call the callback if any 
    if (onClose) { 
     try { 
     onClose(); 
     } 
     catch (e) { 
     } 
    } 
    }); 

    // true = opened the widget 
    return true; 
} 

用途:

$('#btnAddWidget').click(function() { 
    var button = this; 

    if (openWidget(handleClose)) { 
    // Opened the widget, disable our button 
    button.disabled = true; 
    } 

    function handleClose() { 
    // Widget was closd, re-enable the button 
    button.disabled = false; 
    } 
}); 

Live example

显然,按钮的禁用仅适用于您需要的;如果你不这样做,只是用这样的:

设置:

var WIDGET_MARKUP = 
    "<div class='widget'>I'm the widget. " + 
    "<span class='close'>Close</span>" + 
    "</div>"; 

// Opens the widget, returns true; if the widget is already 
// open, doesn't open a a second and returns false. 
function openWidget(onClose) { 
    var widget; 

    widget = $(WIDGET_MARKUP); 
    widget.appendTo(document.body); 
    widget.delegate('span.close', 'click', function() { 
    // Remove the widget 
    widget.remove(); 

    // Call the callback if any 
    if (onClose) { 
     try { 
     onClose(); 
     } 
     catch (e) { 
     } 
    } 
    }); 
} 

用途:

$('#btnAddWidget').click(function() { 
    openWidget(); 
}); 

Live example

+0

非常感谢,它的工作非常感谢! – 2011-02-24 19:31:48

+0

@Jeevan:不客气,很高兴帮助。 – 2011-02-24 21:27:02